C: filling an array with random numbers in a range

你说的曾经没有我的故事 提交于 2021-01-29 21:22:53

问题


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:

  1. It would be better to add srand(time(NULL)); once before calling rand() so that your code can generate different random numbers at different runtime.

  2. rand() % 9 + 1 will generate numbers in the range [1, 9]. So int array1[10]; can be changed to int array1[9]; to save some memory. But if you need numbers in the range [1, 10] then don't change that but change rand() % 9 + 1 to rand() % 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!