if 语句贯穿始终,无论是否满足条件

If statement runs through whether conditions are met or not

本文关键字:是否 满足 条件 语句 if      更新时间:2023-10-16

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 而不是检查值,因此它永远不会退出。