Question:掷两个骰子。每个骰子有六面,检查两个骰子的和。如果和为2、3或12(称为掷骰子),你就输了;如果和为7或11(称作自然),你就赢了;但如果和是其他数字,就确定了一个点。继续掷骰子,直到掷出一个7或掷出和刚才相同的点数。如果掷出的是7,你就输了。如果掷出的点数和你前一次掷出的点数相同,你就赢了。
以下是用C++来编写的一个程序来解决这个问题。
方法1:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// 获取当前时间的秒数,用于生成随机数种子
srand(static_cast<unsigned int>(time(nullptr)));
int point = 0;
while (true) {
// 掷两个骰子,计算点数
int dice1 = rand() % 6 + 1;
int dice2 = rand() % 6 + 1;
int sum = dice1 + dice2;
cout << "玩家掷出了" << dice1 << "和" << dice2 << ",点数为" << sum << endl;
// 判断掷出的点数是否为胜利点数
if (sum == 7 || sum == 11) {
cout << "玩家胜利!" << endl;
break;
} else if (sum == 2 || sum == 3 || sum == 12) {
cout << "庄家胜利!" << endl;
break;
} else {
if (point == 0) {
// 确定点数
point = sum;
cout << "玩家确定了点数" << point << endl;
} else if (sum == 7) {
cout << "庄家胜利!" << endl;
break;
} else if (sum == point) {
cout << "玩家胜利!" << endl;
break;
}
}
}
return 0;
}
方法2:
#include<iostream>
#include<ctime>
using namespace std;
void main()
{
int last=0;
srand((unsigned)time(0));
int a,b;
while(1)
{
a=rand()%6+1;
b=rand()%6+1;
cout<<"你掷出了"<<a<<"和"<<b<<" ";
if(last==0)
{
if(a+b==2||a+b==3||a+b==12)
{
cout<<"你输了"<<endl;
break;
}
if(a+b==7||a+b==11)
{
cout<<"你赢了"<<endl;
break;
}
}
else
{
if(a+b==7)
{
cout<<"你输了"<<endl;
break;
}
else if(a+b==last)
{
cout<<"你赢了"<<endl;
break;
}
}
last=a+b;
cout<<"继续掷骰子"<<endl;
system("pause");
}
}
这两个方法都可以实现,免费复制哦!