我一直被困在C++問題上大約一個半小時。這裏的問題是:隨機整數/事件(C++)問題
編寫一個程序,生成0到9之間的一百個隨機整數,並顯示每個數字的計數。 (提示:使用rand() %10生成一個介於0和9之間的隨機整數。使用一個由10個整數組成的數組,012次表示計數,以存儲O的個數,1,...,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;
}
謝謝,這很有幫助 – jtarr523 2013-05-03 23:46:29
@ jtarr523請記住,只要你一遍又一遍地複製相同的代碼,你應該重新考慮你在做什麼。 – 2013-05-03 23:47:58
@ jtarr523如果有幫助,不要忘記接受答案。 – 2013-05-03 23:58:04