首页 > 解决方案 > 如果仍然不满足要求,我如何制作重复自身的 if 语句?

问题描述

这是我的代码。

#include <iostream>

using namespace std;

int main()
{

    int i = 0;

    int players;
    int silenceAmount;
    int bleedAmount;
    int bleedDays;
    int playersAlive;
    int playersDead;
    int playersAllowed = 6;

    cout << "How many players are playing (can only be " << playersAllowed << ")? ";
    cin >> players;
    if (players > playersAllowed) (
            cout << "There an only be " << playersAllowed << " players. Please select another number. ");
            cin >> players;

    cout << "There are " << players << " players.\n\n";



    return 0;

}

这只能工作一次,我希望它工作直到它得到一个小于或等于 6 的数字。

标签: c++

解决方案


重复if语句通常作为while循环完成。在您的代码中,当您有

if (players > playersAllowed)

你应该简单地改变它

while (players > playersAllowed)

另外,当我在做的时候,你的if语句的语法对于你正在尝试做的事情是不正确的。您应该分别替换(and和)。此外,结束括号的位置不正确。{}

最后,您的循环将是这样的:

while (players > playersAllowed) {
    cout << "There can only be " << playersAllowed << " players. Please select another number: ";
    cin >> players;
}

请注意,这不考虑有人输入jfksdjfs数字。


推荐阅读