珠海市网站开发公司电话,织梦商业网站内容管理系统,sun v2.1 wordpress主题,godaddy wordpress 备c 语言#xff0c; 随机数#xff0c;一个不像随机数的随机数
使用两种方式获取随机数#xff0c;总感觉使用比例的那个不太像随机数。
方法一#xff1a; rand() 获取一个随机数#xff0c;计算这个随机数跟最大可能值 RAND_MAX#xff08;定义在 stdlib.h 中#xf…c 语言 随机数一个不像随机数的随机数
使用两种方式获取随机数总感觉使用比例的那个不太像随机数。
方法一 rand() 获取一个随机数计算这个随机数跟最大可能值 RAND_MAX定义在 stdlib.h 中的比例数值再用需要的范围 100 跟这个相乘得到一个随机数方法二直接用 rand() % 100 取余。
下面是两种方法获取到的 100 个数值
#include stdio.h
#include stdlib.h
#include time.hint 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 i0;i100; 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 i0;i100; 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);
}
结果