我参加了C编程课程,在我们的家庭作业中,我们的教授要求我们编写一个程序,生成一个千位数组并存储随机数(范围从5到15)。然后,它需要显示每个数字出现的次数(以及其他计算)。我已经设法做到这一切,但效率非常低。正如您在我的代码中所看到的,我已经使用了一堆 if 语句,我可能已经使用了 for 循环。能帮我改进一下这段代码吗?我无法使用指针或重新排列数组。谢谢!
main()
{ 的printf(" -------------------------------------------- ---------------------------- \ n&#34); printf("这个程序生成一个带有随机值的一千个数字数组\ n" "范围从5到15.它还计算所有这些数字的总和,\ n" "他们的平均值,并计算每个数字。\ n"); 的printf(" -------------------------------------------- ---------------------------- \ n \ n&#34);
int i,count5=0,count6=0, count7=0, count8=0, count9=0,
count10=0, count11=0, count12=0, count13=0, count14=0, count15=0, sum = 0;
float avg;
int a[1000] = {0};
srand(time(NULL));
for(i=0; i<=999; i++)
{
a[i] = (rand()%11)+5;
if(a[i] == 5)
{
count5 = count5++;
}
if(a[i] == 6)
{
count6 = count6++;
}
if(a[i] == 7)
{
count7 = count7++;
}
if(a[i] == 8)
{
count8 = count8++;
}
if(a[i] == 9)
{
count9 = count9++;
}
if(a[i] == 10)
{
count10 = count10++;
}
if(a[i] == 11)
{
count11 = count11++;
}
if(a[i] == 12)
{
count12 = count12++;
}
if(a[i] == 13)
{
count13 = count13++;
}
if(a[i] == 14)
{
count14 = count14++;
}
if(a[i] == 15)
{
count15 = count15++;
}
sum = sum + a[i];
}
printf("Sum of entire array = %d\n",sum);
avg = sum/1000.0;
printf("Average of values in array = %.2f\n\n",avg);
printf("Fives: %d\n",count5);
printf("Sixes: %d\n",count6);
printf("Sevens: %d\n",count7);
printf("Eights: %d\n",count8);
printf("Nines: %d\n",count9);
printf("Tens: %d\n",count10);
printf("Elevens: %d\n",count11);
printf("Twelves: %d\n",count12);
printf("Thirteens: %d\n",count13);
printf("Fourteens: %d\n",count14);
printf("Fifteens: %d\n\n",count15);
}