2

我目前在 C++ 问题上停留了大约一个半小时。这是问题:

编写一个程序,生成 100 个 0 到 9 之间的随机整数并显示每个数字的计数。(提示:使用 rand() % 10 生成 0 到 9 之间的随机整数。使用一个由十个整数组成的数组,比如 counts,来存储 O、l、...、9 的数量。)

这就是我到目前为止所拥有的。我想我已经很接近了,但是对于每个随机整数的出现(或计数),我不断得到“0”。任何帮助将不胜感激。

const int SIZE = 100;

int main()
{
int integers[SIZE];
int index;
int zero = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;

cout << "The following 100 integers are random:" << endl;
cout << endl;

srand(time(0));

for (index = 0; index < SIZE; index++)
{
    integers[SIZE] = rand() % 10;
    cout << integers[SIZE] << " ";
}

cout << endl;

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 0)
    {
        zero += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 1)
    {
        one += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 2)
    {
        two += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 3)
    {
        three += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 4)
    {
        four += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 5)
    {
        five += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 6)
    {
        six += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 7)
    {
        seven += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 8)
    {
        eight += 1;
    }
}

for (index = 0; index < SIZE; index++)
{
    if (integers[index] == 9)
    {
        nine += 1;
    }
}

cout << "The number of zeros in the random list are " << zero << endl;
cout << "The number of ones in the random list are " << one << endl;
cout << "The number of twos in the random list are " << two << endl;
cout << "The number of threes in the random list are " << three << endl;
cout << "The number of fours in the random list are " << four << endl;
cout << "The number of fives in the random list are " << five << endl;
cout << "The number of sixes in the random list are " << six << endl;
cout << "The number of sevens in the random list are " << seven << endl;
cout << "The number of eights in the random list are " << eight << endl;
cout << "The number of nines in the random list are " << nine << endl;

getch();

return 0;

}
4

1 回答 1

7

您有未定义的行为,因为您将SIZE其用作数组的索引而不是index

for (index = 0; index < SIZE; index++)
{
    integers[SIZE] = rand() % 10;
    cout << integers[SIZE] << " ";
}

这将访问数组边界之外(因为范围是 from0SIZE-1)。在循环体内,更改SIZEindex.

但是,我认为它会帮助你重新阅读你的问题陈述。具体来说:

使用一个由十个整数组成的数组,例如counts来存储 0、1、...、9 的数量

相反,您使用数组来存储随机数。这根本没有必要。您不需要跟踪生成的数字。您只需将 1 添加到适当的计数,然后您可以简单地丢弃随机数。

您应该简单地拥有一个名为 的数组counts,其中counts[0]存储0到目前为止的 s 数量,counts[1]存储 s 的数量1等。然后您不需要这些名为zero, one,等的可怕变量two。如果您发现自己定义了这样的变量名称(其中的数字越来越多),那么您可能应该改用数组。

于 2013-05-03T23:37:34.060 回答