bool和statemetns的问题

时间:2015-09-21 14:58:22

标签: c++ if-statement boolean

我在c ++中尝试使用的某些代码存在问题,它是3个测试分数的平均值,而cout会给你平均值,但如果平均值相等则需要bool变量100%那么它会显示一串"恭喜你收到一个完美的"如果它不是100%,除了他们的平均值之外什么都不会出现,但我一直得到#34; Congrats"即使平均值不是100%也会出现

#include <iostream>
using namespace std;

int main ()

{
int score1, score2, score3;
    cout << "Enter your 3 test scores and I will \n";
    cout << "average them: ";
    cin >> score1 >> score2 >> score3 ;
double average;
    average = (score1 + score2 + score3) / 3.0;
    cout << "Your average is " << average << endl;
    bool perfectScore;
    if(average = 100)
        perfectScore = true;
    else
        perfectScore = false;
    if(perfectScore == true)
        cout << "Congratulations! \n";
        cout << "That's a perfect score. \n";
        cout << "you deserve a pat on the back! \n";

        return 0;

}

2 个答案:

答案 0 :(得分:2)

使用if(average == 100)(比较)代替if(average = 100)(分配)。

你也可以使用一个块。

if(perfectScore == true) { /* add { */
    cout << "Congratulations! \n";
    cout << "That's a perfect score. \n";
    cout << "you deserve a pat on the back! \n";
} /* add } */

答案 1 :(得分:0)

(编辑:这不是解决问题的答案,这是一个简单的建议)

写if条款时要小心,

if(perfectScore == true)
    cout << "Congratulations! \n";
    cout << "That's a perfect score. \n";
    cout << "you deserve a pat on the back! \n";

    return 0;

也许你的意思是所有cout行都在这个if的主体中,但它们不是。你写的东西等同于这个,

if(perfectScore == true) {
    cout << "Congratulations! \n";
}
cout << "That's a perfect score. \n";
cout << "you deserve a pat on the back! \n";

return 0;

因为默认情况下,如果不包括括号,if将只包含其后的第一个语句。即使你写了一行if总是明确地写括号也不是坏事。

你应该怎么做,

if(perfectScore == true) {
    cout << "Congratulations! \n";
    cout << "That's a perfect score. \n";
    cout << "you deserve a pat on the back! \n";
}
return 0;