Ericnth的小站

  • 你可能还想了解...
  • 首页
  • 编程学习笔记
  • 系统与软件
  • 摄影
  • 随笔
  • 论坛
  • 公告

C++随机函数

  • Zhang, Xuheng
  • 2020-04-07
  • 0

1.随机函数可以随机选取在一个规定范围内的数。

2.特殊公式:(1)要取得[a,b)的随机整数,使用(rand()%(b-a))+a;

(2) 要取得[a,b]的随机整数,使用(rand()%(b-a+1))+a;

(3) 要取得(a,b]的随机整数,使用(rand()%(b-a))+a+1;

3.通用公式:a+rand()%n.

4.时间种子:在主程序中定义变量后写一句"srand(time(0));

作用:使每次随机输出的结果不同。

5.举例:

例1:随机输出一个651~685的整数。

程序如下:

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    srand(time(0));
    n=rand()%35+651;    //685-651+1=35
    cout<<n;
    return 0;
}

你可能还想了解...

  • A Bayesian Analysis of High School Acceptance Rates in Shanghai
  • HYRing项目代码解读
  • 算法讲解之贪心算法(转)
  • 算法讲解之回溯法(转)
  • C/C++ IDE推荐
© 2023 Ericnth的小站
Theme by Wing
沪ICP备2020025694号 沪公网安备31011202012861号
  • {{ item.name }}
  • {{ item.name }}