c 语言, 随机数,一个不像随机数的随机数

c 语言, 随机数,一个不像随机数的随机数

使用两种方式获取随机数,总感觉使用比例的那个不太像随机数。

  • 方法一: rand() 获取一个随机数,计算这个随机数跟最大可能值 RAND_MAX(定义在 stdlib.h 中)的比例数值,再用需要的范围 100 跟这个相乘,得到一个随机数;
  • 方法二:直接用 rand() % 100 取余。

下面是两种方法获取到的 100 个数值:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

int get_random_within(double max){
   
    float ratio = rand()/(double)RAND_MAX;
    return (int)(max * ratio);
}

int main(){
   
    time_t t;
    srand(time(&t));
    printf("time is %lu", t);

    printf("\n\nuse random ratio to RAND_MAX to get random values: \n");
    for (int i=0;i<100; i++){
   
        if (i> 0 && i % 10 == 0){
   
            printf("\n");
        }
        int temp = get_random_within(100);
        if (temp < 10){
   
            printf(" %d ", temp);
        } else {
   
            printf("%d ", temp);
        }
    }

    printf("\n\nuse %% to get random values: \n");
    for (int i=0;i<100; i++){
   
        if (i > 0 && i % 10 == 0){
   
            printf("\n");
        }
        int temp = rand() % 100;
        if (temp < 10){
   
            printf(" %d ", temp);
        } else {
   
            printf("%d ", temp);
        }
    }

    printf("\n");
    return(0);
}


结果

在这里插入图片描述

相关推荐

  1. 明明随机数C语言

    2023-12-29 17:44:03       56 阅读
  2. C++ 随机数

    2023-12-29 17:44:03       34 阅读
  3. c++ 随机数

    2023-12-29 17:44:03       30 阅读
  4. C语言关于随机数知识点总结

    2023-12-29 17:44:03       35 阅读
  5. 生成随机数C++

    2023-12-29 17:44:03       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-29 17:44:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-29 17:44:03       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-29 17:44:03       87 阅读
  4. Python语言-面向对象

    2023-12-29 17:44:03       96 阅读

热门阅读

  1. k8s 工具开源项目搜集 —— 筑梦之路

    2023-12-29 17:44:03       58 阅读
  2. 矩阵理论基本知识

    2023-12-29 17:44:03       50 阅读
  3. HACCP认证需要什么条件

    2023-12-29 17:44:03       62 阅读
  4. 由麦克斯韦方程组推出均匀平面电磁波及其特征

    2023-12-29 17:44:03       51 阅读
  5. 景区购票小程序开发案例分析

    2023-12-29 17:44:03       52 阅读
  6. NI VeriStand中的硬件I / O延迟时间

    2023-12-29 17:44:03       54 阅读
  7. php伪类型

    2023-12-29 17:44:03       61 阅读
  8. 基于vue2+elementUI年份范围选择器

    2023-12-29 17:44:03       59 阅读
  9. Leetcode8-最常见的单词(819)

    2023-12-29 17:44:03       56 阅读