此代码的目的:模拟100场CRAPS比赛并记录第一轮赔率,第一轮胜利,第二轮亏损PLUS积分和第二轮胜利PLUS积分。
那些不熟悉CRAPS规则的人;你基本上掷了两个骰子,如果结果是除了总共2,3或12之外的其他任何东西,你就可以再次滚动(你转动的那个数字被保留并加到你的点上)。如果您掷出7或11,则自动获胜。
这是我到目前为止所处的位置:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main ()
{
int i,d1,d2,sumd,sumd2;
double winf = 0, lostf = 0, winp = 0, lostp = 0;
printf("This program will simulate the game of craps for 100 times.\n");
for (i=0; i<100; i++) {
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd = d1 + d2;
if (sumd==7 || sumd==11) {
printf("You rolled a 7 or an 11, you win.\n");
winf++;
}
if (sumd==2 || sumd==3 || sumd==12) {
printf("You rolled a 12, a 3, or a 2, you lose.\n");
lostf++;
}
if (sumd==4 || sumd==5 || sumd==6 || sumd==8 || sumd==9 || sumd==10) {
while (1) {
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd2 = d1 + d2;
if (sumd2==sumd){
printf("You rolled your points, you win.\n");
winp++;
break;}
if (sumd==7){
printf("You rolled a 7, you lose.\n");
lostp++;
break;}
}
}
}
printf("First roll wins: %lf, First roll loses: %lf, Second roll wins: %lf, Second roll loses: %lf. ", winf, lostf, winp, lostp);
}
我问你的是,你给我的选项是如何保留最后打印的那些点?
此外,我觉得我的代码写得更好,冗余更少,建议?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main ()
{
int i,d1,d2,sumd,sumd2;
double winf = 0, lostf = 0, winp = 0, lostp = 0;
printf("This program will simulate the game of craps for 100 times. Press any key to continue.\n");
//getchar();
for (i=0; i<100; i++) {
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd = d1 + d2;
switch(sumd){
case 7:
case 11:
printf("You rolled %d, you win.\n", sumd);
winf++;
break;
case 2:
case 3:
case 12:
printf("You rolled %d, you lose.\n", sumd);
lostf++;
break;
default:
while (1) {
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd2 = d1 + d2;
if (sumd2==sumd){
printf("You rolled your points(%d), you win.\n",sumd);
winp++;
break;}
if (sumd2==7){
printf("You rolled a 7, you lose.\n");
lostp++;
break;}
}
}
}
printf("First roll wins: %lf, First roll loses: %lf, Second roll wins: %lf, Second roll loses: %lf. \n", winf, lostf, winp, lostp);
}
答案 0 :(得分:2)
你宁愿轻易地压缩两次出现的
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd2 = d1 + d2;
成一个函数:
int rolldice(){
int d1,d2;
d1 = rand()%6+1;
d2 = rand()%6+1;
return d1 + d2;
}
或以单行形式:
int rolldice(){
return (rand()%6)+(rand()%6)+2;
}
然后你会写
sumd = rolldice();
答案 1 :(得分:1)
将结果放入最后打印的解决方案看起来很合理。如果我理解正确的问题,似乎winp和lostp应该添加sumd2而不是仅仅增加。或者它已经正常工作,我误解了这个问题?
您可能还想查看switch
声明:
switch(sumd){
case 7:
case 11:
//existing code goes here
break;
case 2:
case 3:
case 12:
//more existing code
break;
default:
//code for games that don't end on the first turn
break;
}