if 语句贯穿始终,无论是否满足条件
If statement runs through whether conditions are met or not
My 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;
}
}
这
真的很假
if (bob == "no", "No", "NO", "nO")
您需要用逻辑 OR 来打破它
if (bob == "no" || bob == "No" || bob == "NO" || bob == "nO")
就目前而言,此if (bob == "no", "No", "NO", "nO")
等效于逗号运算符的效果if("nO")
。
bob == "no", "No", "NO", "nO"
没有做你认为它正在做的事情。你的意思是要做:
bob == "no" ||
bob == "No" ||
bob == "NO" ||
bob == "nO"
这是您问题的旁注,但在这种情况下,您可能需要考虑在比较答案之前将答案转换为小写(或大写)。
这样,您就可以使用if (tolower(bob) == "no")
下面是如何使用tolower
函数的示例
http://www.cplusplus.com/reference/cctype/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;
}
您的循环问题可以解释为:
while (continueBool = true)
应改为
while (continueBool == true)
.
按照您的代码当前情况,您将其设置为 true 而不是检查值,因此它永远不会退出。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- "<"满足严格的弱排序是否意味着不需要"=="定义?
- 在不再满足条件后,while 循环是否停止验证?
- 什么 STL 算法可以确定容器中的一个项目是否满足谓词?
- C++概念是否允许我的类在声明/定义中指定它满足某些概念?
- 检查是否所有 std::元组元素都满足条件 + 设计问题
- 检查变量是否满足没有呼叫的过载功能
- 在运行时询问变体中的替代是否满足某个概念
- 当满足条件时,是否可以在 GLSL 着色器中回调 C/C++ 函数/代码
- if 语句贯穿始终,无论是否满足条件
- g++是否满足std::string C++11的要求
- CRTP-从基类中检查派生类是否满足要求
- 检查是否满足任意不等式的列表
- C++该类型是否应满足std::is_copy_assignable
- 浮点数的无限是否满足这些方程
- 如何确保我的代码是ansi C,不涉及C++.像gcc这样的编译器是否可以设置为在满足C++中的功能时提示错误
- 检查循环中出现的任何条件是否已满足c++
- 循环中字符串的输出会根据是否满足某个条件而变化
- 在C++如何验证是否满足某些条件