ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

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

2026/9/12 14:10:45 拓冰建站 浏览量
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);
}

结果

在这里插入图片描述