#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
// Use these variables in a switch statement to count each digit.
int x0 = 0, x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0,
x6 = 0, x7 = 0, x8 = 0, x9 = 0, num;
for (int i = 0; i < 5; i++) {
num = rand() % 1000;
printf("%d\n", num);
switch (num % 10) { // Splits third digit and counts.
case 0: x0++; break;
case 1: x1++; break;
case 2: x2++; break;
case 3: x3++; break;
case 4: x4++; break;
case 5: x5++; break;
case 6: x6++; break;
case 7: x7++; break;
case 8: x8++; break;
case 9: x9++; break;
}
switch (num/10 % 10) { // Splits second digit and counts.
// add case statements
}
switch (num/100 % 10) { // Splits first digit and counts.
// add case statements
}
}
printf("You have %d 0 digits.\n", x0); // Testing
printf("You have %d 1 digits.\n", x1);
return 0;
}
我想在0-999之间生成200个随机数字,将它们分成数字,并获得每个数字的频率计数而不使用任何数组。我玩弄了一下,想出了如何拆分一个数字(以相反的顺序)以及如何生成随机数字。现在我该如何拆分所有200个数字并将这些数字存储在变量中,我可以使用这些数字?我是否需要三个变量,分别命名为digit1
,digit2
,digit3
?如何分割C中的随机数并获得每个数字的频率计数而不使用数组?
注意:这是作业,所以我不允许使用数组,并且必须使用switch
语句来计算每个数字的频率。
您需要10个变量来存储计数,例如, count0,count1,... count9。数字可以循环提取,除非你不允许使用循环:/ – user3386109
我被允许使用循环,幸好哈哈。 –
你不应该被允许在一个源文件':-)'中扔太多换行和空间不足' – chqrlie