我对 C(以及一般编程)非常陌生,并且几乎不可能理解如何操作数组(我知道数组是什么)。
我正在尝试编写一个程序,在范围(1-50)中生成100个随机整数,并将它们存储在数组元素中(1-10、11 -20、21-30、31-40和41-50),并打印每个元素中存储的随机生成的整数的数量,即
- 1-10 = 20
- 11-20 = 30
- 21-30 = 21
- 31-40 = 19
- 41-50 = 20
到目前为止我能想到的最好的是:
void randomNumbers
{
int count[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = rand() % 50 + 1;
}
for (int i = 0; i <= ARRAY_LENGTH - 1; i++)
{
printf("Index %d -> %d\n", i, count[i]);
}
}
这只是说“元素 1 = 随机数,元素 2 = 随机数”等等。
我不明白如何:
- 将随机生成的整数存储在数组元素中
- 将随机生成的整数划分为相应的 元素
- 告诉程序打印每个生成的整数的数量 元素范围
最佳答案
以下代码生成 100 个随机整数,并根据其值将它们分组:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, temp;
int a[5]; // array to store the frequency
for(i=0;i<5;i++)
a[i]=0;
srand(time(0)); // for generating new random integers on every run
for(i=0;i<100;i++)
{
temp = (rand()%50) + 1; // generates random integers b/w 1 to 50
a[(temp-1)/10]++;
}
for(i=0;i<5;i++)
printf("%d->%d = %d\n",i*10+1,(i+1)*10,a[i]); //printing in the desired format
return 0;
}
关于C:创建随机生成的整数,将它们存储在数组元素中,并打印每个元素中存储的整数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243259/