题目大致是这样的:投2个色子,如果2个色子的和为7或11时,游戏者赢;如果2个色子的和为2,3,12时,游戏者输;
如果2个色子的和为3、4、5、6、8、9、10的其中一个时,将这个和作为游戏者的点数,再给
游戏者7次机会,如果在7次内能够投出刚才投出的数字和时,游戏者赢,反之,输。
下面是书上给的程序例子:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
int rollDice(void);//因为rollDice函数不取参数,所以在参数表中用void来声明。
int main()
{
enum Status {CONTINUE,WON,LOST};
int sum,
myPoint;
Status gameStatus;//给game注释
srand(time(NULL));
sum=rollDice();//第一次投色子
switch (sum)
{
case 7:
case 11:
gameStatus=WON;//第一次投就赢
break;
case 2:
case 3:
case 12:
gameStatus=LOST;//第一次投就输
break;
default: //记住除上述外所投的点数
gameStatus=CONTINUE;
myPoint=sum;
cout<<"Point is"<<myPoint<<endl;
break;
}
while(gameStatus==CONTINUE) //继续投色子
{
sum=rollDice();
if (sum==myPoint) //当符合点数时,赢
gameStatus=WON;
else if (sum==7) //投到7时,输;而题意是投7次,我保证题目是这么说的。
gameStatus=LOST;
}
if (gameStatus==WON)
cout<<"Player wins!"<<endl;
else
cout<<"Player loses!"<<endl;
return 0;
}
int rollDice (void)
{
int die1,
die2,
workSum;
die1=1+rand()%6;
die2=1+rand()%6;
workSum=die1+die2;
cout<<"Player rolled"<<die1<<"+"<<die2<<"="<<workSum<<endl;
return workSum;
我觉得是编程者的失误。否则这么判断的话,意图好像前后有矛盾。
我自己用计数器改了一下:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
int rollDice(void);//因为rollDice函数不取参数,所以在参数表中用void来声明。
int count=0;
int main()
{
enum Status {CONTINUE,WON,LOST};
int sum,
myPoint;
Status gameStatus;//给game注释
srand(time(NULL));
sum=rollDice();
switch (sum)
{
case 7:
case 11:
gameStatus=WON;
break;
case 2:
case 3:
case 12:
gameStatus=LOST;
break;
default:
gameStatus=CONTINUE;
myPoint=sum;
cout<<"Point is"<<myPoint<<endl;
break;
}
while(gameStatus==CONTINUE)
{
sum=rollDice();
if (sum==myPoint)
gameStatus=WON;
else if (count==8)\\这里应该是用7还是8,用7的话,只有6次投色子
gameStatus=LOST;
}
if (gameStatus==WON)
cout<<"Player wins!"<<endl;
else
cout<<"Player loses!"<<endl;
return 0;
}
int rollDice (void)
{
int die1,
die2,
workSum;
die1=1+rand()%6;
die2=1+rand()%6;
workSum=die1+die2;
++count;
cout<<"Player rolled"<<die1<<"+"<<die2<<"="<<workSum<<endl;
return workSum;
}
[此贴子已经被作者于2006-5-29 15:06:18编辑过]