c++ - 如果仍然不满足要求,我如何制作重复自身的 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 的数字。
解决方案
重复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
数字。
推荐阅读
- blazor - 使用 Blazor 在循环中激活多个复选框
- vue.js - Vue-Tables-2 端服务器获取错误“无法读取未定义的属性‘数据’”为什么?
- java - 从传递的参数将对象转换为类
- javascript - Photoshop CEP 面板 - 选择 json 文件的路径
- python - 使用python在ModbusRTU中同时调用多个寄存器?
- php - PHP 意外的文件结尾,在 jwt 登录页面中
- mysql - Kafka Mysql Connector plugin.path 配置
- python - 如何根据命令运行定时器?
- jquery - 为传单 L.Draggable 对象设置包含
- jquery - 如何在 each() 函数中设置密钥?