我正在做一本书练习,写一个生成伪随机数的程序.我开始简单了.
#include "std_lib_facilities.h"
int randint()
{
int random = 0;
random = rand();
return random;
}
int main()
{
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
cout << randint() << endl;
keep_window_open();
}
Run Code Online (Sandbox Code Playgroud)
我注意到每次运行程序时都会有相同的"随机"输出.所以我调查了随机数生成器并决定尝试播种,首先在randint()中包含它.
srand(5355);
Run Code Online (Sandbox Code Playgroud)
这只是反复生成相同的数字(我现在感觉很愚蠢.)
所以我认为我会聪明并实现这样的种子.
srand(rand());
Run Code Online (Sandbox Code Playgroud)
这基本上只是与程序在第一时间做的相同,但输出了一组不同的数字(这是有道理的,因为rand()生成的第一个数字总是41.)
我能想到的唯一让它更随机的是:
我是否在我脑海中,我现在应该停下来吗?选项2难以实施吗?还有其他想法吗?
提前致谢.
我正在尝试使用该rand()函数生成伪随机整数.它的工作原理,但我的问题是它始终为int选择相同的名称.(在这种情况下,它是41.我想如果你把rand()主要的while循环放在85或者什么东西.)
有没有办法来解决这个问题?这是我的代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int guess;
int danse = rand() % 101;
using namespace std;
void more(){
cout << "The number that you need to guess is higher!";
return;
}
void lower(){
cout << "The number that you need to guess is lower!";
return;
}
int main(){
while(1){
cout << "\nGuess a number 0-100: ";
cin >> guess;
if (guess > danse){
lower();
}
if (guess < danse){
more();
}
if (guess …Run Code Online (Sandbox Code Playgroud)