我的if语句贯穿始终,好像条件已经满足,即使他们没有。我已经尝试过移动代码,甚至以不同的方式重写if语句,但它没有改变结果。有谁知道我做错了什么?
#include <iostream>
#include <string>
using namespace std;
double num, num2, num3, num4, num5, num6, sum;
char input;
bool continueBool = true;
string bob;
void math()
{
cout << "Please enter your first number" << endl;
cin >> num;
cout << "Please enter your second number?" << endl;
cin >> num2;
cout << "Please enter your third number?" << endl;
cin >> num3;
cout << "Please enter your fourth number" << endl;
cin >> num4;
cout << "Please enter your fith number?" << endl;
cin >> num5;
cout << "Please enter your sixth number?" << endl;
cin >> num6;
sum = num + num2 + num3 + num4 + num5 + num6;
}
void ifStatement() {
if (bob == "no", "No", "NO", "nO") {
continueBool = false;
cout << "Good bye!" << endl;
}
}
int main()
{
while (continueBool = true) {
math();
cout << "The sum of your numbers is: " << sum << endl;
cout << "Would you like to add any more numbers together?" << endl;
cin >> bob;
ifStatement();
return 0;
}
}
答案 0 :(得分:2)
这真是虚假
if (bob == "no", "No", "NO", "nO")
您需要使用逻辑OR而不是
来突破它if (bob == "no" || bob == "No" || bob == "NO" || bob == "nO")
按照目前的情况,这个if (bob == "no", "No", "NO", "nO")
与逗号运算符的效果等同于if("nO")
。
答案 1 :(得分:0)
bob == "no", "No", "NO", "nO"
没有做你认为它正在做的事情。你的意思是:
bob == "no" ||
bob == "No" ||
bob == "NO" ||
bob == "nO"
答案 2 :(得分:0)
这是您的问题的一个附注,但在此上下文中,您可能需要考虑在比较之前将答案转换为小写(或大写)。
这样,你可以使用if (tolower(bob) == "no")
以下是如何使用tolower
函数
/* tolower example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
char str[]="Test String.\n";
char c;
while (str[i])
{
c=str[i];
putchar (tolower(c));
i++;
}
return 0;
}
答案 3 :(得分:0)
你的循环问题可以解释:
while (continueBool = true)
应该阅读
while (continueBool == true)
。
正如您的代码当前所示,您将其设置为true而不是检查值,因此它永远不会退出。