布尔和if语句的问题
Problems with bool and if statemetns
我在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;
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- Craps游戏问题,忽略if语句
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 有人能在我的代码中找到与C++中的IF语句相关的问题吗
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 如果 GPA 计算器的语句问题
- C++:关于for语句和参数的一般问题
- 为什么当我从语句检查中删除"+ mod"时,以下程序给出错误的答案。问题链接:https://www.codechef.com/problems/FFC219B
- C++字符串和 while 语句的问题
- 使用语句if时逻辑的问题
- C - 如果语句问题.代码将不会运行其他,否则
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 在设置 if-else 语句以删除特定货币并保持更新时遇到问题
- 如果/else语句未显示/可变分配问题的输出;初学者程序员
- 在循环中与开关语句有问题
- If/Else 语句在 2D 数组中移动时出现问题
- 从类模块检索信息以在 switch 语句中输出时出现问题
- 我的 IF 语句中存在问题,否则无法正常工作
- C++函数问题中的 IF 语句