简体   繁体   中英

C: Create randomly-generated integers, store them in array elements, and print number of integers stored in each element

I'm incredibly new to C (and programming in general) and finding how to manipulate arrays is almost impossible to understand (I know what an array is).

I'm attempting to write a program that generates 100 random integers in a range (1-50) , stores them in array elements (1-10, 11-20, 21-30, 31-40, and 41-50), and print the number of randomly generated integers stored in each element, ie

  • 1-10 = 20
  • 11-20 = 30
  • 21-30 = 21
  • 31-40 = 19
  • 41-50 = 20

The best I can come up with so far is:

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

在此处输入图片说明

That just says "element 1 = random number, element 2 = random number" etc.

I don't understand how to:

  • Store the randomly-generated integers in the array's elements
  • Partition the randomly-generated integers into the corresponding element
  • Tell the program to print the number of integers generated in each element range

The following is the code that generates 100 random integers and groups them into categories based on their value :

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM