0x012B1CA9处的未处理异常

时间:2016-04-24 23:04:08

标签: c++ arrays random

我是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;
};

2 个答案:

答案 0 :(得分:0)

我认为阅读有关C数据类型和声明的更多内容基本上是个好主意。你的错误:

const int MAX = '100'应为const int MAX = 100,不带任何引号。 C ++从字符文字隐式转换为int

答案 1 :(得分:0)

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

更改此行

const int MAX = '100';

const int MAX = 100;

请注意已移除的单引号。

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

但最好使用C++'s random header

中的算法

以下是原始代码的更正版本....

#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;
};