C语言随机算法

0~100

 1 #include <stdio.h>
 2 #include <stdlib.h>//包含srand和rand函数
 3 #include <time.h>//包含time函数
 4 
 5 int main (int argc,char* argv[])
 6 {
 7   //随机种子
 8   srand((unsigned int)time(NULL));
 9   //把0~100的随机数赋给x变量
10   int x = rand() % 100;
11   
12   return 0;
13 }

给定范围的随机数,格式(x~y):rand % (y - x) + x(注:x为负数也可以哦)

举个例子(10~99):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(int argc, char* argv[])
{
  srand((unsigned int)time(NULL));
  int x = rand() % (100 - 10) + 10; //rand() % (100 - 10)毕竟是取余,最后结果取不到90,最高89,所以上界只能是89+10=99
  return 0;
}

看到有的文章推广给定范围的随机数格式为rand % y + x,

确实可以满足下界一定是x,但无法满足上界,上界最大可能会达到y+x(x是正数的情况,负数技巧性的反过来)

posted @ 2022-02-10 13:31  SkySource  阅读(130)  评论(0编辑  收藏  举报