为什么算法在第一个条件后结束?

时间:2016-02-28 18:30:52

标签: c++ algorithm loops

我正在设计一个数字猜测算法用作游戏。

任何人都可以建议为什么算法在第一个条件之后结束?

#include <iostream>

using namespace std;

int main()
{

int num = 5;
int guess;

cout << "Guess a number \n";
cin >> guess;


if (guess==num)
{
    cout << "You guessed the correct number \n";
}
else if (guess < num)
{
    cout << "Your guess is lower than the number \n";
    cout << "Guess again \n";
    cin >> guess;
}
else
{
    cout << "Your guess is higher than the number \n";
    cout << "Guess again \n";
    cin >> guess;
}


return 0;

}

2 个答案:

答案 0 :(得分:0)

如果您希望重复该算法,则需要某种循环。

例如

#include <iostream>

using namespace std;

int main()
{
    int num = 5;
    int guess;

    cout << "Guess a number \n";

    do
    {
        cin >> guess;

        if ( guess == num )
        {
            cout << "You guessed the correct number \n";
        }
        else if ( guess < num )
        {
            cout << "Your guess is lower than the number \n";
            cout << "Guess again \n";
        }
        else
        {
            cout << "Your guess is higher than the number \n";
            cout << "Guess again \n";
        }

    } while ( guess != num );

    return 0;
}

答案 1 :(得分:0)

如果你想再次猜测我推荐一个循环。否则,您的代码将按预期工作。

while(number != guess)
        {
            if(number * 2 < guess){
                cout << "Way to high. Try again." << endl;
                cin >> guess;
            }

            if(number / 2 > guess)
            {
                cout << "Tip : My number is NOT low. Try again." << endl;
                cin >> guess;
            }

            if(number < guess)
            {
                cout << "To high try something lower. Feed me a number." << endl;
                cin >> guess;
            }
            if(number > guess)
                cout << "To low, try again." << endl;
                cin >> guess;
        }