C ++如果循环错误

时间:2015-12-03 17:03:55

标签: c++ loops if-statement

我正在尝试制作一个可以猜出你输入数字的程序。我对自己的错误感到困惑。程序编译,一切正常,但到了一定程度。该程序一直有效,直到它在猜测2次后要求您输入。第三次程序退出。比如说我的号码是700.该程序将首次猜测500。由于700超过500,您可以选择“更高”选项(下面的代码)。程序会将变量“Low”从0改为500,即当前猜测。然后它会将“低”添加到“高”(第一次猜测时为1000)并将答案更改为“猜测”变量。然后它将采用“猜测”变量并将其除以2,使其成为新的猜测,然后将其打印出来作为程序中的猜测。因此,如果数字超过500,则第二个猜测将是750.现在这个等式将改变。它会将“高”变量更改为当前猜测,并再次将“低”添加到“高”。答案将改为猜测,然后再分为2,给出625.由于700仍然高于625,它将再次使用第一个输入的等式。但不是这样做,程序就会退出。有帮助吗?如果我需要进一步详细说明(再次),请说出来。 我假设我在if循环中做错了什么

if (status == ...)

等等。

代码:

#include #include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main ()
{
int number,low,high,guess,guesses,status;
low = 0;
high = 1000;
guesses = 0;
cout<<"Please pick a number between 1 and 1000 \n";
do
    {
        cin>>number;
        if (number > 1000) cout<<"Please pick a number less than 1000 \n";
    } while (number > 1000);
cout<<"Thank you. Now I will guess your number! \n";
guess=500;
cout<<"Is your number "<<guess<<"? \n";
cout<<"[1] Yes \n"<<"[2] Higher \n"<<"[3] Lower \n";
do
    {
        cin>>status;
        if ( (status != 1) && (status != 2) && (status != 3) ) cout<<"Please select option 1, 2, or 3 \n";
    } while ( (status != 1) && (status != 2) && (status != 3) );
do
    {   
        if (status == 2)
        low=guess;
        guess=low+high;
        guess=guess/2;
        guesses=guesses+1;
        cout<<"Is your number "<<guess<<"? \n";
        cout<<"[1] Yes \n"<<"[2] Higher \n"<<"[3] Lower \n";
        cin>>status;
        if (status == 3)
        high=guess;
        guess=low+high;
        guess=guess/2;
        guesses=guesses+1;
        cout<<"Is your number "<<guess<<"? \n";
        cout<<"[1] Yes \n"<<"[2] Higher \n"<<"[3] Lower \n";
        cin>>status;
        if (status == 1)
        cout<<"I guessed your number! It only took me "<<guesses<<" tries to guess it!";
    } while ( (status = 3) && (status = 2) && (status = 1) );
return 0;

}

1 个答案:

答案 0 :(得分:1)

你肯定有一些有问题的代码。例如,

if (status = 2);

这是为了什么目的?首先,如果您想比较status是否等于2,则正确的语法是:

if (status == 2)

其次,即使语法正确,行也以分号(;)结尾。这意味着如果if条件为真,则会执行一个空语句。

最后,在发布此类问题时,请指出导致错误的行。 Stackoverflow代码清单不显示行号,期望有人计算所有行,以便他们可以帮助您,这有点不合理。