我在1到10之间生成20个随机数。然后我使用switch语句来获取1到10之间每个可能随机数的计数。
我想知道是否有另一种方法可以使用循环显示一系列变量,而不是像我下面那样手动构建表格:
for (int i = 0; i < 20; i++)
{
a[i] = generateRandomNumber();
//record the counts for each possible random number
switch (a[i]) {
case 0: ++count_1; break;
case 1: ++count_2; break;
case 2: ++count_3; break;
case 3: ++count_4; break;
case 4: ++count_5; break;
case 5: ++count_6; break;
case 6: ++count_7; break;
case 7: ++count_8; break;
case 8: ++count_9; break;
case 9: ++count_10; break;
}
}
//output the counts to the screen
cout << "N Count\n";
cout << "1: " << ++count_1 << "\n";
cout << "2: " << ++count_2 << "\n";
cout << "3: " << ++count_3 << "\n";
cout << "4: " << ++count_4 << "\n";
cout << "5: " << ++count_5 << "\n";
cout << "6: " << ++count_6 << "\n";
cout << "7: " << ++count_7 << "\n";
cout << "8: " << ++count_8 << "\n";
cout << "9: " << ++count_9 << "\n";
cout << "10: " << ++count_10 << "\n";
谢谢!
答案 0 :(得分:3)
您可以使用数组来计算所有数字的出现频率 - :
int count[10];
for ( int i = 0; i < 10; i++ )
{
count[i] = 0; // Initializing count
}
for ( int i = 0; i < 20; i++ )
{
a[i] = generateRandomNumber();
count[a[i]]++;
}
//output the counts to the screen
cout << "N Count\n";
for ( int i = 0; i < 10; i++ )
{
cout << i + 1 << " : " << count[i] << "\n";
}