C++,随机数,范围为 1-6
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4665832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++, random number w/ range of 1-6
提问by TLM
I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.
我想知道使用 rand() 方法获取范围为 1-6 的随机数的方法是什么。这是为了模拟我需要的骰子卷,以找到 3 个骰子卷的平均值,因此类型将是双倍。
回答by Nylon Smile
This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
这是一个在 1 到 6 之间生成随机数的简单示例,我想您可以计算其余部分
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0));
std::cout << (rand() % 6 + 1) <<std::endl;
return 0;
}