
初级C++里rand的用法-三个随机筛子游戏
这是一道很简单的使用rand的问题,使用C++程序滚动3个骰子,显示这些骰子的值,并显示三颗骰子加起来的总和。下面是我写的,本来应该要随机出现三个值的,但是我运行了之后,...
这是一道很简单的使用rand的问题,使用C++程序滚动3个骰子,显示这些骰子的值,并显示三颗骰子加起来的总和。 下面是我写的,本来应该要随机出现三个值的,但是我运行了之后,一直都是显示一样的值,有人能帮我找到问题出在哪里吗?(PS:因为我还是新手,写的东西很简单,拜托了)
#include <iostream>
using namespace std;
int main()
{
int d1;
int d2;
int d3;
int total;
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
d3 = rand() % 6 + 1;
cout << "The 1st Dice is " << d1 << endl;
cout << "The 2nd Dice is " << d2 << endl;
cout << "The 3rd Dice is " << d3 << endl;
total = d1+d2+d3;
cout << "The Total value of these dices is " << total << endl;
return 0;
} 展开
#include <iostream>
using namespace std;
int main()
{
int d1;
int d2;
int d3;
int total;
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
d3 = rand() % 6 + 1;
cout << "The 1st Dice is " << d1 << endl;
cout << "The 2nd Dice is " << d2 << endl;
cout << "The 3rd Dice is " << d3 << endl;
total = d1+d2+d3;
cout << "The Total value of these dices is " << total << endl;
return 0;
} 展开
2个回答
展开全部
你的随机数是编译生成的,需要使用随机数种子才能生成真的随机数。
srand(time(0));
需要头文件
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int d1;
int d2;
int d3;
int total;
srand(time(0));
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
d3 = rand() % 6 + 1;
cout << "The 1st Dice is " << d1 << endl;
cout << "The 2nd Dice is " << d2 << endl;
cout << "The 3rd Dice is " << d3 << endl;
total = d1+d2+d3;
cout << "The Total value of these dices is " << total << endl;
return 0;
}
srand(time(0));
需要头文件
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int d1;
int d2;
int d3;
int total;
srand(time(0));
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
d3 = rand() % 6 + 1;
cout << "The 1st Dice is " << d1 << endl;
cout << "The 2nd Dice is " << d2 << endl;
cout << "The 3rd Dice is " << d3 << endl;
total = d1+d2+d3;
cout << "The Total value of these dices is " << total << endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询