[英]C: Craps / Dice Game
該代碼的目的:模擬CRAPS的100場比賽,並記錄第一輪損失,第一輪勝利,第二輪損失加分和第二輪勝利加分的數量。
你們中那些不熟悉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);
}
您可以輕松地將兩個事件的發生濃縮
d1 = rand()%6+1;
d2 = rand()%6+1;
sumd2 = d1 + d2;
進入aa函數:
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();
您將結果以int結尾的解決方案看起來很合理。 如果我理解正確的問題,似乎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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.