使用C中随机产生不同的号码 [英] Generate different numbers in C using Random

查看:146
本文介绍了使用C中随机产生不同的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我在C写这个函数生成从1 5随机数到50:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释主(){
    INT C,N;    的printf(1五随机数到50 \\ n);    为(C = 1; C< = 5; C ++){
        N =兰特()%50 + 1;
        的printf(%d个\\ N,N);
    }    返回0;
}

和我想知道我怎么能确定这个code产生的数字是从彼此完全不同。

任何帮助吗?


解决方案

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&time.h中GT;无效掉期(INT *一,为int * B){
    INT TEMP = *一个;
    * A = * B;
    * B =温度;
}诠释主(){
    INT I,C,N,大小= 50;
    int数据[大小]    函数srand(时间(NULL));
    对于(i = 0; I<大小; ++ I)
        数据[I] = i + 1的;    的printf(1五随机数到50 \\ n);    为(C = 1; C< = 5; C ++){
        N =兰特()%的大小;
        的printf(%d个\\ N,数据[N]);
        掉期(安培;数据[ - 大小],和放大器;数据[N]);
    }    返回0;
}

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 ?

解决方案

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

这篇关于使用C中随机产生不同的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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