C ++程序计算错误

时间:2015-05-14 15:06:24

标签: c++

#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。然后将这些乘法的所有结果加在一起。

在此程序中尽可能使用函数。您可以通过作为参数传入要在解释性cout中显示的字符串来创建函数来获取输入。以下是一个示例运行:

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社区。

1 个答案:

答案 0 :(得分:3)

这些行不正确

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

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

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

第一种方法计算一些临时float,然后立即抛弃它,因为它没有被分配给任何东西。事实上,编译器可能只会抛出整条线。