0x012B1CA9时未处理的异常

Unhandled exception at 0x012B1CA9

本文关键字:异常 未处理 0x012B1CA9      更新时间:2023-10-16

我是C++新手,正在尝试构建一个简单的程序,随着用户的输入继续,它将生成一个随机的左或右。我让程序正常工作,直到我添加数组以尝试存储每个项目,因为我必须尽快输出它们并且用户想要退出循环。该程序似乎编译良好,但在运行时我收到"0x012B1CA9未处理的异常" 任何帮助将不胜感激。

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
    cout << "Press 1 to pick a side or 0 to quit: ";
    cin >> userSelection;

    for (int i = 1; i < MAX; i++)
    {
        srand(time(NULL));
        sel[i] = 1 + (rand() % 2);
        if (sel[i] == 1)
        {
            cout << "<<<--- Left" << endl;
            one++;
            total++;
        }
        else
        {
            cout << "Right --->>>" << endl;
            two++;
            total++;
        }
    }

} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
    cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};

你这里有一个多字符常量...并且行为没有按预期进行...

更改此行

const int MAX = '100';

const int MAX = 100;

请注意删除的单引号。

其次,我建议您从 for 循环中删除 C 随机生成器的种子,因为如果您总是在播种后立即调用它,您可能会从rand()中获得相同的值......

但最好使用C++随机标头中的算法

这是原始代码的更正版本。

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100;     // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
    cout << "Press 1 to pick a side or 0 to quit: ";
    cin >> userSelection;

    srand(time(NULL));    //< moved to here
    for (int i = 0; i < MAX; i++)     // <-- modified starting index
    {
        sel[i] = 1 + (rand() % 2);
        if (sel[i] == 1)
        {
            cout << "<<<--- Left" << endl;
            one++;
            total++;
        }
        else
        {
            cout << "Right --->>>" << endl;
            two++;
            total++;
        }
    }

} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
    cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
我认为阅读

更多关于 C 数据类型和声明的信息基本上是个好主意。您的错误:

const int MAX = '100'应该const int MAX = 100,没有任何引号。C++ 执行从字符文字到int的隐式转换。