zoukankan      html  css  js  c++  java
  • C/C++生成随机数

    1、c语言生成随机数

    ​ 需要的头文件:#include<stdlib.h>

    ​ #include<time.h>

    ​ 需要使用的函数:rand()、srand()、time()

    rand()函数的使用
      int n = rand();
    

    ​ 生成一个随机数n

    ​ 接下来,来点更灵活的,让n的取值在-5~55之间:

    ​ 于是我们想到了用取模,0<= n%61 <=60,n%61减5,得 -5<= n%61-5 <=55,则

    	  int x = n%61-5;	// 等价于 int x = rand()%61-5;
    

    ​ 生成-5~55范围内的随机数x,其它任何范围同理。

    srand()和time()函数的使用

    ​ 上述生成的随机数每次运行都是相同的,并非是真正意义上的随机数,要生成真正意义上的随机数需要1.2中两个函数的辅助。srand()是种子函数,1.1中未调用该函数,系统默认种子数为1,所以每次运行都是同一个值。time()是调用系统时间的函数。

    ​ 生成真正意义上的随机数代码如下:

        #include<stdio.h>
        #include<stdlib.h>
        #include<time.h>
    	int main()
        {
            srand(time(0));
            int x = rand()%61-5;
            return 0;
        }
    

    2、c++生成随机数

    ​ c++生成随机数和c同理,只要改一下头文件即可,代码如下:

    	#include<iostream>
    	#include<cstdlib>
    	#include<ctime>
    	int main()
        {
            srand(time(0));
            int x = rand()%61-5;
            return 0;
        }
    
  • 相关阅读:
    Codeforces 451A Game With Sticks
    POJ 3624 Charm Bracelet
    POJ 2127 Greatest Common Increasing Subsequence
    POJ 1458 Common Subsequence
    HDU 1087 Super Jumping! Jumping! Jumping!
    HDU 1698
    HDU 1754
    POJ 1724
    POJ 1201
    CSUOJ 1256
  • 原文地址:https://www.cnblogs.com/godfriend/p/10782632.html
Copyright © 2011-2022 走看看