Generate different numbers in C using Random [dupl

2019-09-21 04:29发布

问题:

This question already has an answer here:

  • Generating random numbers in C 7 answers

So basically i wrote this function in C to generate 5 random numbers from 1 to 50:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int c, n;

    printf("Five random numbers from 1 to 50 \n");

    for (c = 1; c <= 5; c++) {
        n = rand()%50 + 1;
        printf("%d\n", n);
    }

    return 0;
}

and i'd like to know how can i be sure that the numbers generated by this code are all different from each other.

Any help ?

回答1:

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

void swap(int *a, int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int i, c, n, size = 50;
    int data[size];

    srand(time(NULL));
    for(i=0;i<size;++i)
        data[i] = i+1;

    printf("Five random numbers from 1 to 50 \n");

    for (c = 1; c <= 5; c++) {
        n = rand()%size;
        printf("%d\n", data[n]);
        swap(&data[--size], &data[n]);
    }

    return 0;
}


回答2:

Store each number in an array and check each new random number against the existing entries.



回答3:

You should check all numbers like this:

#include <time.h>

int randomNumbers[5];
int c, d, n;
bool itIsNew;

//current time as random seed
srand(time(0));

for (c = 1; c <= 5;)
{
    n = rand() % 50 + 1;
    itIsNew = true;

    for(d = 1; d <= c; d++)
    {
        if(n == randomNumbers[d - 1])
        {
            itIsNew = false;
            break;
        }       
    }
    if(itIsNew)
    {
        randomNumbers[c - 1] = n;
        c++;
    }
}


标签: c random