我一直在努力为我在学校的实验室制作一个主谋程序,从1到6个随机数。我运行了我的代码来查找此错误:
Debug Assertion失败!
程序:C:\ windows \ SYSTEM32 \ MSVCP140D.dll文件:c:\ program files (x86)\ microsoft visual studio 14.0 \ vc \ include \ vector Line:1232
表达式:向量下标超出范围
有关程序如何导致断言的更多信息 失败,请参阅关于断言的Visual C ++文档。
(按“重试”调试应用程序)
我已尝试重试,但它打开了另一个对话框,说调试到达了一个断点,此时我无法继续调试。 这是我感兴趣的代码(Microsoft Visual Studio编译器):
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void getRandoms(vector<int> &random);
void getGuesses(vector<int> &guess);
void checkGuesses(const vector<int> &random, const vector<int> guess);
int main()
{
srand(time(0));
vector<int> random(4, 0);
vector<int> guess(4, 0);
getRandoms(random);
cout << "Welcome to Mastermind" << endl << endl;
getGuesses(guess);
checkGuesses(random, guess);
system("pause");
return 0;
}
void getRandoms(vector<int> &random)
{
for (int i = 0; i < 4; i++)
{
random[i] = (rand() % 6) + 1;
}
cout << "answer key: " << random[1] << " " << random[2] << " " << random[3] << " " << random[4] << endl;
}
void getGuesses(vector<int> &guess)
{
cout << "Please enter your four numerical guesses (space separated): ";
for (int j = 0; j < 4; j++)
cin >> guess[j];
cout << endl << endl;
}
void checkGuesses(const vector<int> &random, const vector<int> guess)
{
int clocat = 0;
int cnumb = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j && random[i] == guess[j])
clocat = clocat + 1;
else if (i != j && random[i] == guess[j])
cnumb = cnumb + 1;
}
}
if (clocat == 4)
cout << "Correct!" << endl << endl << "You are a MasterMind!";
else
cout << "You have " << cnumb << " correct number(s) and " << clocat << " correct location(s)." << endl << endl;
}
我怀疑这是我错误使用矢量的错误,但我无法查明错误。谢谢你的帮助!
答案 0 :(得分:3)
void getRandoms(vector<int> &random)
{
for (int i = 0; i < 4; i++)
{
random[i] = (rand() % 6) + 1;
}
cout << "answer key: " << random[0] << " " << random[1] << " " << random[2] << " " << random[3] << endl;
}
答案 1 :(得分:2)
cout << "answer key: " << random[1] << " " << random[2] << " " << random[3] << " " << random[4] << endl;
以上行是导致错误的原因。
如果您尝试访问代码中的 4th 索引,则会导致分段错误。