问题描述:

Hi I want to know is there a way to store randnumber without prompting user for input. In this example we want user to store 16 randnumbers in array storerand without prompting the user for randnums for example:

#include<stdio.h>

#include<stdlib.h>

void main() {

int randnum;

int i=0;

int storerand[16]; // storing randnumbers

randnum=rand();

while(i <16){

storerand[i]=randnum; // why is this not storing 16 rand number how can i store 16 randnumbers

i++;

}

return 0;

网友答案:

An easy way to generate random numbers in C is to use the rand() function which comes with <stdlib.h>. Note that if you do not seed with the time library, you will receive the same random numbers every time you run your program.

#include <stdlib.h>
#include <time.h>

int main (void) {
    //Uses system time to seed a proper random number.
    srand(time(NULL));
    //rand() generates a random integer
    int a = rand();
    //Use mod to restrict range:
    int b = rand()%5; //random integer from 0-4
    return 0;
}

You also need to make sure to increment your index i within your while loop.

while(i < 16) {
    storerand[i] = rand(); 
    i++;
}
网友答案:

You initialise randnum with a random value here:

randnum=rand();

And then you run your loop to put its value into each slot of your array. That means you're putting the same value into each slot.

while(i <16){
    storerand[i]=randnum;
    i++;
}

The solution is to call rand() each time around the loop:

for( i = 0; i < 16; i++ ) {
    storerand[i] = rand();
}
相关阅读:
Top