[英]'rand' function in C++?
我正在尝试制作一个死亡预测因子,让你的角色随机死亡。 我会让它有多次死亡机会,以及你成长年龄越大的机会。 我如何修复这个基本的rand函数,使其成为如此int RandomFactor有一个1-20数字并随机激活以杀死你(对不起,如果这听起来像虐待狂)?
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand(time(NULL));
int RandomFactor;
RandomFactor = rand();
20 % 1;
for (double count = 0; count < 20; count++) {
if (count < 20) {
Sleep(360);
cout << "\n\t\t\tIt's your birthday! You turned: " << count;
}
else
if (RandomFactor == 1) {
cout << "\n\n\n\t\t\tBANG! You're dead!";
}
}
cout << "\n\n\n\t\t\t ";
return 0;
}
你可以使用rand % 20
但它不会真正统一,它会包含偏见。 C ++中更好的选择是以这种方式使用std::uniform_int_distribution<>
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen( rd());
std::uniform_int_distribution<> dis( 1, 20);
for ( int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
您可以阅读此内容以了解有关rand() % x
引入的偏差的更多信息。
C ++允许您随意丢弃值,所以当您这样做时
20 % 1;
它没有抱怨,因为它计算它并简单地抛出值。
也许你的意思实际上是:
RandomFactor = rand() % 20;
但是,这将导致[0,19]范围内的数字,所以您可能想要添加1:
RandomFactor = (rand() % 20) + 1
所以现在范围的两端将增加1,导致[1,20]包含。
此外,if语句
if(count < 20)
循环时总是如此(毕竟是循环条件),所以else if
永远不会运行。
尝试使用drand()
,它将返回0到1之间的统一数字,然后您可以进行缩放。 您可以使用srand48(seed)
进行初始化。 例如,如果您想要20%的机会触发,您可以执行以下操作:
if( drand() <= 0.05f ) // (5% chance)
// do something
或者
int randomNumber = ceil( drand()*20 );
// creates a uniform distribution between 1 and 20, inclusive
在rand()之后不应该有一个分号。 尝试RandomFactor = rand()20%1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.