Cha*_*ola 2 c++ random loops for-loop if-statement
我正在尝试制作一个死亡预测因子,让你的角色随机死亡.我会让它有多次死亡的机会,以及你成长年龄越大的机会.我如何修复这个基本的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;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用,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';
}
Run Code Online (Sandbox Code Playgroud)
您可以阅读此内容以了解有关引入的偏差的更多信息rand() % x.