我想显示随机数特定范围[from, to]。以下代码写出该值,但某些内容无法正常工作:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int draw(int from_to, int to_from)
{
return (rand()%to_from)+from_to;
}
int main()
{
srand(time(NULL));
int start,stop;
cout << "First number: " << endl;
cin >> start;
cout << "Last number: " << endl;
cin >> stop;
int x=20;
do
{
cout << draw(start,stop) << endl;
x--;
} while(x>0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试从指定范围生成随机数的 C++11 功能:
#include <random>
#include <iostream>
int main() {
int from = 0;
int to = 100;
std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<std::mt19937::result_type> distribution(from, to);
std::cout << distribution(generator) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)