对于循环技巧

时间:2016-07-15 13:53:45

标签: c++ for-loop

我制作了这段代码,提示用户输入的数字不是5,否则游戏结束。如果用户输入10次号码,则应显示获胜消息。但是,如果用户输入5,我发现自己很难不显示获胜消息。如果用户输入5而不是两者都打印失败消息,我该怎么办?还有,有一种方法可以使我的代码更简单吗?

for (int i = 0; i < 10; i++)
{
    cout << i+1 << "- enter a number: ";
    cin >> number;

    if (number == 5)
    { cout << "you were not supposed to enter 5!\n"; // Failure message
      break;
    }
}

cout << "Wow, you're more patient than I am, you win.\n"; // winner message

6 个答案:

答案 0 :(得分:3)

一种方法是在i扩展范围并检查:

int i = 0;
for (; i < 10; i++)
{
    cout << i+1 << "- enter a number: ";
    cin >> number;

    if (number == 5)
    {
      cout << "You were not supposed to enter 5!\n"; // Failure message
      break;
    }
}

if (i == 10)
{
    cout << "Wow, you're more patient than I am, you win.\n"; // winner message
}

另一种方法是使用布尔标志:

bool win = true;
for (int i = 0; i < 10; i++)
{
    cout << i+1 << "- enter a number: ";
    cin >> number;

    if (number == 5)
    {
        cout << "You were not supposed to enter 5!\n"; // Failure message
        win = false;
        break;
    }
}

if (win)
{
    cout << "Wow, you're more patient than I am, you win.\n"; // winner message
}

答案 1 :(得分:1)

循环结束有两个原因之一:用户输入10个非5个,或者他们输入5打破循环。因此,只需检查循环后number的值是什么,以区分两者。

答案 2 :(得分:1)

您可以将整个for循环放在一个返回boolean / int的函数中 然后在if

中调用该函数

像:

if(game()==true)
   cout << "Wow, you're more patient then I am, you win.\n"; // winner message
else
   cout << "you were not supposed to enter 5!\n";  // Failure message

把东西放在一个函数中是作业:)

提示:用功能内的返回替换couts;)

答案 3 :(得分:1)

你需要使用flag,一个可能的解决方案是(这也使你的代码更简单):

bool win = true;
for (int i = 0; i < 10 && win; i++)
{
    cout << i+1 << "- enter a number: ";
    cin >> number;

    win = number != 5;
}
if( win ) 
    cout << "Wow, you're more patient then I am, you win.\n"; // winner message
else
    cout << "you were not supposed to enter 5!\n"; // Failure message

答案 4 :(得分:0)

一个简单的布尔标志将解决您的问题。

bool enteredFive = false;
for (int i = 0; i < 10; i++)
{
    cout << i + 1 << "- enter a number: ";
    cin >> number;

    if (number == 5)
    {
        cout << "You were not supposed to enter 5!" << endl;
        enteredFive = true;
        break;
    }
}

if (!enteredFive)
    cout << "Wow, you're more patient then I am, you win!" << endl;

答案 5 :(得分:0)

使用标志变量[Here isFive]检查用户是否曾输入5并根据该决定进行打印。

bool isFive = false;
for (int i = 0; i < 10; i++)
{
    cout << i+1 << "- enter a number: ";
    cin >> number;

    if (number == 5)
    { 
      isFive = true;
      cout << "you were not supposed to enter 5!\n"; // Failure message
      break;
    }
}
if(!isFive)
   cout << "Wow, you're more patient then I am, you win.\n"; // winner message