Any random number in a range that allows a computer to be random in a C + + language

Source: Internet
Author: User

This is part of the question I met in the written test, which is recorded. For example, output any random number in [1,3].

1#include <iostream>2#include <cstdlib>3#include <cstdio>4#include <ctime>5 6 7 intMain ()8 {9 Srand ((unsigned) time (NULL));Ten  One     intval =0; A      for(inti =0; I < -; i++) -     { -val = (rand ()%3) +1; theStd::cout << i +1<<" "<< Val <<Std::endl; -     } -     return 0; -}

What does line nineth mean in the code?

In the C language, the rand () function can be used to generate random numbers, but this is not the true meaning of the random number, is a pseudo-random number, is based on a number, we can call it a seed, as a reference to a recursive formula derived from a coefficient, when the series of a large number of times, it is normal to publish, This is equivalent to generating a random number, but this is not a true random number, when the computer is properly booted, the value of this seed is fixed, unless you destroy the system, in order to change the value of this seed, C provides the Srand () function, its prototype is void Srand (int a)

1) First give Srand () a seed, it is a unsigned int type, its value range from 0~65535;

2) then call Rand (), which returns a random number (between 0 and 32767) based on the seed value provided to Srand ()

inductive : To obtain a random integer between [a, b], use (rand ()% (b-a)) + A or (rand () * (b-a))/Rand_max + A

REF:

http://blog.csdn.net/qin_zhangyongheng/article/details/8033936

Any random number in a range that allows a computer to be random in a C + + language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.