对于循环技巧

For loop tricks

本文关键字:循环 于循环      更新时间:2023-10-16

我制作此代码是为了提示用户输入一个不是 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

一种方法是在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
}
循环

结束的原因有两个:用户输入了 10 个非 5,或者他们输入了中断循环的 5。 因此,只需检查循环后number的值是多少,以区分两者。

您可以将

整个for循环放在返回布尔值/整数的函数中然后在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 替换为函数;)内的回车符

你需要使用 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

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

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;

使用标志变量 [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
int number;
for (int i = 0; i < 10; i++)
{
    std::cout << i + 1 << "- enter a number: ";
    std::cin >> number;
    if (number == 5)
    {
        std::cout << "you were not supposed to enter 5!n"; // Failure message
        return 0;
    }
    
    
}
std::cout << "Wow, you're more patient than I am, you win.n"; // winner message