布尔和if语句的问题

Problems with bool and if statemetns

本文关键字:问题 语句 if 布尔      更新时间:2023-10-16

我在c++中试图纠正的一些代码有问题,这是3个测试分数的平均值,cout会给你平均值,但它需要一个bool变量,但即使平均值不是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;
}

使用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 } */

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

写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;