C:用一定范围内的随机数填充数组 [英] C: filling an array with random numbers in a range

查看:63
本文介绍了C:用一定范围内的随机数填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C和数组完成以下任务:

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到10 范围内的数字:

As mentioned in comments , if you want number in range 1 to 10 :

array0[i]= rand()%10 + 1;

我建议使用 int array1 [10] = {0}; 代替此循环:

I suggest int array1[10]={0}; instead of this loop:

for(int i = 0 ; i < 10 ; i++)
{
  array1[i]= 0;
}

这是印刷的完整代码:

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]);
    }
}

也正如@Ardent Coder所说,添加 srand(time(NULL)); bfeore rand()在不同的运行时生成不同的随机数.

also as @Ardent Coder said add srand(time(NULL)); bfeore rand() to generate different random numbers at different runtimes.

这篇关于C:用一定范围内的随机数填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆