抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

C语言生成伪随机数:

  1. 头文件加入:

    1
    2
    #include <stdlib.h>
    #include <time.h>
  2. 添加这段代码:

    1
    srand((unsigned int)time(0));
  3. 然后就可以调用这段代码生成随机数了:

    1
    2
    3
    4
    5
    rand();

    //直接调用即可,如:
    int a = rand();
    A[i] = rand();
  4. 实际使用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    int main(){
    int A[10];
    srand((unsigned int)time(0));
    printf("这是给A[]随机赋的值:\n");
    for(int i=0; i<10; i++){
    //直接调用即可
    A[i]=rand();
    printf("第%d次:%d\n", i+1, A[i]);
    }
    return 0;
    }

    运行结果:

    imaged59b07debf5b3ed0.png

评论