使用rand()生成变量周围的数字?(C++)
Using rand() to generate numbers around a variable?(C++)
我正在用c++制作一个名为"House Evolution"的基于文本的小游戏,以获得乐趣。游戏包括"在沙发垫下搜索"以获得积分。当你搜索时,游戏应该生成一个从creditRate-5到creditRate+5的随机数。不管creditRate是多少,我该如何使用rand((函数来完成这项工作?以下是示例代码:
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <math.h>
int main()
{
int creditRate = 30; // Just for example.
int credits;
int searching;
while (1) {
// Yes, I know, infinite loop...
std::cout << "Credits: " << credits << std::endl;
std::cout << "Type any key to search for credits: " << std::endl;
std::cout << "Searching...n";
usleep(10000000); // Wait 10 seconds
searching = rand(?????????); // Searching should be creditRate-5 to creditRate+5
std::cout << "You found " << searching<< " creditsn";
credits += searching;
}
}
我的方法是使用兰特%11,得到11个数字的范围,然后将其添加到信用率-5,以覆盖从信用率-5到信用率+5的范围。因此:
searching = rand() % 11 + creditRate - 5;
尝试:searching = rand() % 11 + creditRate-5;
这是因为你的范围是11(记住,例如,从-5到5有11个数字(,下限是creditRate-5。
使用<random>
标头而不是rand()
,因为<random>
提供了正确生成这些分发的工具,而不是让您自己生成。
#include <iostream>
#include <thread>
#include <random>
int main()
{
int creditRate = 30; // Just for example.
// Searching should be creditRate-5 to creditRate+5
std::uniform_int_distribution<> random_credit_amount(creditRate - 5, creditRate + 5);
int credits = 0;
// arrange a source of randomness
std::random_device r;
std::seed_seq seed{r(),r(),r(),r(),r(),r()};
std::mt19937 pRNG(seed);
while (true) {
// Yes, I know, infinite loop...
std::cout << "Credits: " << credits << 'n';
std::cout << "Type any key to search for credits: " << 'n';
std::cout << "Searching...n";
std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds
int searching = random_credit_amount(pRNG);
std::cout << "You found " << searching<< " creditsn";
credits += searching;
}
}
<random>
甚至提供了比典型的均匀分布更高级的选项。例如,使用"正态"(也称为"钟形曲线"(分布,您可以让更接近creditRate的值比更远的值更有可能,而不是让从creditRate - 5
到creditRate + 5
的每个值都有同样的可能性:
// credits found should be near creditRate
std::normal_distribution<> random_credit_amount(creditRate, 5);
然后在循环中:
int searching = std::round(random_credit_amount(eng));
(你根本不需要改变循环中的代码,但它会使分布有点偏斜。执行适当的舍入可以避免偏斜。(
请注意我所做的另一项更改,用标准this_thread::sleep_for
替换了非标准usleep
。请注意,此代码使注释完全多余:
std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds
人们可以很容易地要求几微秒或几个小时的睡眠时间
std::this_thread::sleep_for(std::chrono::hours(2));
std::this_thread::sleep_for(std::chrono::microseconds(50));
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 如何检查二维数组上的周围数字?
- 运行时检查失败 #2 - 变量"数字选择"周围的堆栈已损坏
- 使用rand()生成变量周围的数字?(C++)