c++程序错误计算

C++ Program miscalculation

本文关键字:计算 错误 程序 c++      更新时间:2023-10-16
#include <iostream>
using namespace std;
// Variables
static float fAssignment, sAssignment, tAssignment, foAssignment, midAssignment, finalAssignment, secAssignment, Total;
// Function to collect the results
float Collector()
{
    printf("Enter the score for the first assignment: ");
        cin >> fAssignment;
    printf("Enter the score for the second assignment: ");
        cin >> sAssignment; 
    printf("Enter the score for the third assignment: ");
        cin >> tAssignment;
    printf("Enter the score for the fourth assignment: ");
        cin >> foAssignment;
    printf("Enter the score for the midterm: ");
        cin >> midAssignment;
    printf("Enter the score for the final: ");
        cin >> finalAssignment;
    printf("Enter the score for the section grade: ");
        cin >> secAssignment;
    return fAssignment, sAssignment, tAssignment, foAssignment, midAssignment, finalAssignment, secAssignment;
}
// Function to calculate the final grade/score
float Calculator()
{
    static float Average = ((fAssignment + sAssignment + tAssignment + foAssignment) / 4) * 0.4f;
    midAssignment * 0.15f;
    finalAssignment * 0.35f;
    secAssignment * 0.1f;
    Total = (Average + midAssignment + finalAssignment + secAssignment);
    return Total;
}

int main() 
{
    Collector();
    Calculator();
    printf("Your score is: ");
    cout << Total << endl;
    return 0;
}

这些是指令以及底部的正确结果

写一个程序来计算你正在学习的一门编程课程的最终成绩。以下是评分方案:

Final grades will be based on the following:
40% Assignments   15% Midterm Examination
35% Final Examination
10% Class Participation Grade 

你的程序应该向用户询问四项作业的分数,期中,期末和部分成绩。然后,计算并打印最终分数。要进行计算,您需要将四个作业的分数平均起来,然后乘以0.4(40%)。然后期中成绩乘以0.15,期末成绩乘以0.35,参与成绩乘以0.1。然后将所有这些乘法的结果加在一起。

在程序中尽可能使用函数。您可以创建一个函数来获取输入,方法是将要在解释性输出中显示的字符串作为参数传入。下面是一个例子:

Enter the score for the first assignment. 75
Enter the score for the second assignment. 85
Enter the score for the third assignment. 82
Enter the score for the fourth assignment. 94
Enter the score for the midterm. 81
Enter the score for the final. 89
Enter the score for the section grade. 100
The final grade is: 86.9

但是当我编译并运行时,我得到了这个结果:

Enter the score for the first assignment: 75
Enter the score for the second assignment: 85
Enter the score for the third assignment: 82
Enter the score for the fourth assignment: 94
Enter the score for the midterm: 81
Enter the score for the final: 89
Enter the score for the section grade: 100
Your score is: 303.6

我使用的是Visual Studio 2013 Community.

这些行不正确

midAssignment * 0.15f;
finalAssignment * 0.35f;
secAssignment * 0.1f;

您需要使用*=来修改这些变量

midAssignment *= 0.15f;
finalAssignment *= 0.35f;
secAssignment *= 0.1f;

第一个方法计算一些临时float,然后立即扔掉它,因为它没有被赋值给任何东西。实际上,编译器可能会把整行代码都扔掉。