如何使用Rand()随机选择变量 [英] How To Randomly Pick A Variable Using Rand()
问题描述
我想用C ++编写一个基于文本的战斗机,这是我做的第一件事之一。到目前为止我有这个:
I am trying to make a text based fighter in C++, this is one of the first things that I have done. So far I have this:
//Text Based Fighter
#include <iostream>
#include <stdlib.h> //srand, rand
#include <string>
using namespace std;
int main() {
//Player
int playerHealth = 100;
int attack1;
int attack2;
int attack3;
string attack;
int npc1;
int npc2;
cout << "Do you want to attack " << rand()[npc1,npc2];
//varname = rand() % 10 + 1;
return 0;
}
我想要做的是在npc1和npc2之间随机选择,谢谢您。
What I am wanting it to do is randomly pick between npc1 and npc2, thank you.
还有关于我如何写我的代码的任何意见将不胜感激,我只是开始几天前谢谢你,如果你需要任何更多的细节,请随意
Also any comments on how I am writing my code would be appreciated, I have only started a couple of days ago thank you, if you need any more detail please feel free to ask, thank you.
推荐答案
对于只有2个选项,您可以使用三元表达式从2取余数:
For just 2 choices you can take the remainder from 2 with a ternary expression:
int choice = rand() % 2 == 0 ? npc1 : npc2;
如果你有两个以上的选择,即使你没有,你可以做一个数组
If you have more than 2 choices, or even if you don't, you can make an array with those and index into it.
int npc_choices[2];
int choice = npc_choices[rand() % 2];
如果选择的数量不是2的幂,你很可能会在用%
运算符进行选择。如果你不是任何具有统计意义或有大量选择的东西,我不会担心。
If the number of choices is not a power of 2 you will likely introduce a very small bias into the selection with the modulo %
operator. If you're not working on anything with statistical significance or with a huge number of choices I wouldn't worry about it.
这篇关于如何使用Rand()随机选择变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!