问题
I am trying accomplish the following tasks using C and arrays:
This is what I could do for now. I also need to print the output. What should I do or edit, thanks.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
array0[i]= rand()%9 + 1;
}
int array1[10];
for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}
int index;
for(int i = 0 ; i < n ; i++)
{
index = array0[i];
array1[index-1]++;
}
}
回答1:
As mentioned in comments , if you want number in range 1 to 10
:
array0[i]= rand()%10 + 1;
I suggest int array1[10]={0};
instead of this loop:
for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}
and here is complete code with printing:
int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
array0[i]= rand()%10 + 1;//for your range
}
int array1[10]={0};
/*for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}*/
int index;
for(int i = 0 ; i < n ; i++)
{
index = array0[i];
array1[index-1]++;
}
for (int i = 0; i < 10; i++)
{
printf("number %d appears:%d\n", i + 1, array1[i]);
}
}
also as @Ardent Coder said add srand(time(NULL));
bfeore rand()
to generate different random numbers at different runtimes.
回答2:
It's fine, you just need to print the output after that:
for (int i = 1; i <= 9; ++i)
printf("\n%d appears %d times", i, array1[i - 1]);
Note:
It would be better to add
srand(time(NULL));
once before callingrand()
so that your code can generate different random numbers at different runtime.rand() % 9 + 1
will generate numbers in the range [1, 9]. Soint array1[10];
can be changed toint array1[9];
to save some memory. But if you need numbers in the range [1, 10] then don't change that but changerand() % 9 + 1
torand() % 10 + 1
and let the printing loop run upto 10.
来源:https://stackoverflow.com/questions/60931951/c-filling-an-array-with-random-numbers-in-a-range