c++ - 为什么即使满足条件,While 循环也会在 C++ 中无限执行?
问题描述
我用C++制作了Rolling Dice Program ,它运行良好,除了While 循环没有中断(attempt != 6)。它会无限地填充随机数(1-6),它应该在尝试 == 6时停止,但它不会。你能调整我的代码并告诉我有什么问题吗?我是 C++ 的初学者。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int attempt = 1+(rand()%6); //random number generating for the Attempts
int numOfAt = 0; //setting value to Number of Attempts
while (attempt != 6 ){
int attempt = 1+(rand()%6);
cout << "You rolled a " << attempt << endl; //keeps executing this line infinitely
numOfAt++;
}
cout << "It took you " << numOfAt << " attempts to roll a six.";
}
解决方案
你有两个attempt
s。attempt
从循环体的外部看不到循环体的内部。while (attempt != 6 )
在循环体之外(循环体之前),所以它看到第一个attempt
,它在循环中没有改变。
要解决此问题,请删除attempt
循环体内的声明并改写attempt
循环之前的内容。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int attempt = 1+(rand()%6); //random number generating for the Attempts
int numOfAt = 0; //setting value to Number of Attempts
while (attempt != 6 ){
attempt = 1+(rand()%6); // remove "int"
cout << "You rolled a " << attempt << endl; //keeps executing this line infinitely
numOfAt++;
}
cout << "It took you " << numOfAt << " attempts to roll a six.";
}
推荐阅读
- node.js - 在 Nodejs 工作线程之间共享大型数据集
- reactjs - 通过 Material UI Theme 更改辅助按钮文本颜色
- ios - ObjC 应用程序构建在 ObjC 静态库中调用 swift 函数时出现构建错误
- google-apps-script - 谷歌应用脚本合并来自多个工作表的数据
- php - PHP JSON在MySQL中编码数字数组
- apache-kafka-streams - Kafka Stream BoundedMemoryRocksDBConfig
- python - 如何在执行 subprocess.Popen 期间杀死由 a 产生的进程?
- python - 放大和缩小 PyGame 窗口,所有对象都在原位
- android - 如何为单元测试生成 Android Key Attestation 格式的证书?
- python - Python Vektor 或矩阵优化