C ++ if / else语句没有正确输出

时间:2015-02-26 00:31:37

标签: c++ if-statement

目前,我遇到了这个if / else语句的问题。这是来源:

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    string firstname, secondname;
    const int A_SCORE = 90;
    const int B_SCORE = 80;
    const int C_SCORE = 70;
    const int D_SCORE = 60;

    int testscore1;
    int testscore2;
    int testscore3;
    int testscore4;
    int testscore5;
    int testscore6;
    int testscore7;
    int testscore8;
    int testscore9;
    int testscore10;

    cout << "Enter your 10 scores and I will average\n"
        << "the total score, and assign letter grades" << endl;

    cin >> testscore1;
    cin.ignore();
    cin >> testscore2;
    cin.ignore();
    cin >> testscore3;
    cin.ignore();
    cin >> testscore4;
    cin.ignore();
    cin >> testscore5;
    cin.ignore();
    cin >> testscore6;
    cin.ignore();
    cin >> testscore7;
    cin.ignore();
    cin >> testscore8;
    cin.ignore();
    cin >> testscore9;
    cin.ignore();
    cin >> testscore10;
    cin.ignore();

    int sum = testscore1 + testscore2 + testscore3 + testscore4 + testscore5 + testscore6 + testscore7 + testscore8 + testscore9 + testscore10;
    int average = sum / 10;

    if (average == 90);
    {
        cout << "your average is an A.";
    }

    else if (average == 80);
    {
        cout << "you have an average of a B.";
    }

    else if (average == 70);
    {
        cout << "you have an average of a C.";
    }

    else  (average == 60);
    {
        cout << "your average is a D.":
    }

    system("pause");

    return 0;
}

这项作业分配的目标是输入10个数字等级,并根据10个等级的平均值对具有字母等级的平均打印输出。无论我输入什么,我总是得到'你的成绩是A.我已经完成了我的笔记广告,以及为了可能出错而寻找goodle / StackOverflow。我也得到编译错误,我无法弄清楚。如果有人可以就可能导致问题的原因向我提出任何想法,我将不胜感激!

3 个答案:

答案 0 :(得分:2)

在if语句后删除分号,而不是检查值是否为90/80/70,请尝试以下方法:

if(average >= 90)
{
//print
}

如果您想要更准确的结果,请尝试使用浮点数而不是整数。

答案 1 :(得分:1)

您的if语句应采用if(average >= 90, 80, etc...)的形式。

另外,你的错误是什么?

编辑:

if (average >= 90)
{
    cout << "your average is an A.";
}

else if (average >= 80)
{
    cout << "you have an average of a B.";
}

else if (average >= 70)
{
    cout << "you have an average of a C.";
}

else if(average >= 60)
{
    cout << "your average is a D.";
}
else
{
    cout << "your average is an F.";
}

return 0;

您需要删除所有分号,一个冒号,将关系运算符从==更改为>=,并添加额外的其他内容以捕获60以下的任何内容。

答案 2 :(得分:1)

If..else语句是有条件的。您需要提供准确的条件以获得您期望的结果。 尝试:

if (average >= A_SCORE)
{
    cout << "your average is an A.";
}

else if (average >= B_SCORE)
{
    cout << "you have an average of a B.";
}

else if (average >= C_SCORE)
{
    cout << "you have an average of a C.";
}

else if(average >= D_SCORE)
{
    cout << "your average is a D.";
}
else
{
    cout << "your average is an F.";
}

system("pause);