C++程序在执行时停止响应
C++ program stops responding on execution
有关我的计算机的基本信息:Windows 7 x64操作系统
8gb内存
使用MingW编译器
所以,每次我在编译完程序后通过终端运行程序时,它都会立即停止响应。我自己似乎找不到这个问题,所以我需要一双额外的眼睛来帮我指出。我现在实际上是C++的初学者,所以请耐心等待。
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <ctime>
using namespace std;
int main()
{
bool correct = false;
srand(time(NULL));
vector<string> guess;
vector<string> pallete;
vector<string> secret;
pallete.push_back("red");
pallete.push_back("green");
pallete.push_back("blue");
pallete.push_back("yellow");
for(int i = 0; i < 4 ; i++)
{
secret.push_back(pallete.at(rand()%secret.size()));
}
for(int j = 0; j < 4 ; j++)
{
guess.push_back(pallete.at(rand()%guess.size()));
}
vector<string> secretMem = secret;
cout << "the guess was:";
for(int x = 0; x<4; x++)
{
cout << guess[x] << endl;
}
while(correct == false)
{
int blackP = 0;
int whiteP = 0;
secret = secretMem;
for (int idxB = 0; idxB < secret.size(); idxB++)
{
if (guess[idxB] == secret[idxB])
{
secret[idxB] = "0";
guess[idxB] = "1";
blackP++;
}
}
for (int idxW = 0; idxW < secret.size(); idxW++)
for (int idyW = 0; idyW < guess.size(); idyW++)
{
if (secret[idxW] == guess[idyW])
{
secret[idxW] = "0";
guess[idxW] = "1";
whiteP++;
}
}
if (blackP == 4)
{
cout << "Congratulations you win." << endl << "The secret code was:"<< endl;
for(int y = 0; y<4; y++)
{
cout << secretMem[y] << endl;
}
correct = true;
}
else
cout << "you scored: " << blackP << " Black pegs" << "and" << whiteP << " White pegs" << endl;
}
return 0;
}
此外。。。。这种糟糕的代码格式是怎么回事。。。。我只是无法像写预览时那样在预览中正确排列…
除以零?secret.size()最初为0。
secret.push_back(pallete.at(rand()%secret.size()));
您正在除以零。
在您的行secret.push_back(pallete.at(rand()%secret.size()));
中,secret.size()为零。根据前面这个问题的答案,Mod 0是"未定义的,可能会抛出‘除以零’异常。"
如果你试图选择一个介于0和最大潜在颜色数之间的数字来猜测,我可能会把这行改为secret.push_back(pallete.at(rand() * pallete.size()-1 ))
。
我想你指的是两个位置的pallete.size(secret.size,guess.size)。然后你有一个无限循环,因为blackP从来都不是4,每个循环都做同样的事情,因为secretMem从来没有更新过。也许在Windows上,它能够处理溢出(不知怎么的?),但却陷入了循环。尽管在这种情况下,你会得到很多"你得分了:0个黑色钉子和1个白色钉子"的线条。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 如何让 c++ 程序执行以响应文件打开
- 确定QProcess是否已完成执行或正在等待用户输入(或响应)
- 需要接受用户的响应才能执行程序
- 如何确定程序在无响应时正在执行的操作
- MFC RIbbon - 同一面板上的多个CMFCRibbonComboBox,响应在任何onComboBox上执行的选
- C++程序在执行时停止响应