gpt4 book ai didi

c++ - 如何在我存储的两个变量之间生成一个随机数?

转载 作者:IT老高 更新时间:2023-10-28 22:05:46 25 4
gpt4 key购买 nike

Possible Duplicate:
Generating random integer from a range

我正在尝试创建一个程序,让计算机猜测用户心中的数字。唯一需要的用户输入是猜测是否太高、太低或正确。我在根据先前的猜测存储最小值和最大值的两个变量之间生成随机数时遇到问题。这是我的代码:

    #include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand(static_cast <unsigned int> (time(0)));

int compGuess = rand() % 100 +1; //Generates number between 1 - 100
int highestNumber = 100;
int lowestNumber = 1;
char ready;
char highLowSuccess;
bool success;
int tries = 0;


cout << "Please pick a number between 1 - 100. I will guess your number. Don't tell me what it is!\n\n";


do
{
cout << "Are you ready? (y/n)\n\n";
cin >> ready;

if (ready == 'y')
{
do
{
cout << "Is your number " << compGuess << "?\n\n";
cout << "High, Low or Success?";
++tries;
cin >> highLowSuccess; //User input telling the computer whether its too high, too low, or a success

if (highLowSuccess == 'h') //Executes code if number guessed was too high.
{

highestNumber = compGuess - 1; //Stores variable indicating the highest possible number based on user input
compGuess = rand() % highestNumber +1; //Generates a new random number between 1 and the new highest possible number
success = false;
}

else if (highLowSuccess == 'l') //Executes code if number guessed was too low.
{
lowestNumber = compGuess + 1;//Stores variable indicating the lowest possible number based on user input
compGuess = (rand() % highestNumber - lowestNumber + 1) + lowestNumber // <---- Not producing the desired result
success = false;
}

else if (highLowSuccess == 's') //Executes code if the computer's guess was correct.
{
cout << "I guessed your number! It only took me " << tries << " tries!";
success = true;
}


} while (success != true);
}


else
{
continue;
}

} while (ready != 'y');



return 0;

}

highestNumber 是最大值,lowestNumber 是最小值。我需要一个方程,让我生成一个随机数,同时考虑可能的最高和最低数字。

如果答案真的很简单,请原谅我,我是一个菜鸟程序员。 xD

最佳答案

要生成介于 min 和 max 之间的随机数,请使用:

int randNum = rand()%(max-min + 1) + min;

(包括最大值和最小值)

关于c++ - 如何在我存储的两个变量之间生成一个随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com