【发布时间】:2016-11-03 22:11:56
【问题描述】:
函数 rand_num 返回 sum,如果 sum 为 7 或 11,则第一次显示为 win,如果为 2、3 或 12,则第一次显示为失败,该步骤正常工作。 当我们有 4、5、6、8、9 和 10 时,问题就来了。如果是,它打印它并请求一个新的随机变量,如程序所示。 // 程序模拟掷骰子游戏
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 6
// function declation
void play_game (int sum); // function for producing the numbers
int rand_num (void); // function for producing the random dice
// function main
int main ()
{
int sum;
// seed random number generaton
srand((unsigned) time(NULL));
sum = rand_num();
play_game (sum);
return 0;
}
// function for producing the random number of the dice and calculating the sum of the dice
int rand_num ()
{
int sum, dice1, dice2;
dice1 = 1 + (rand() % SIZE);
dice2 = 1 + (rand() % SIZE);
sum = dice1 + dice2;
return sum;
}
// function for playing the game craps
void play_game (int sum)
{
// for the first roll of the dice
char command;
do {
// condition for winning for the first roll
if (sum == 7 || sum == 11){
printf ("You rolled %d\n", sum);
printf ("You win!\n");
printf ("\nPlay again ? 'Y' or 'N'\n");
scanf ("%c", &command);
}
// condition for lossing for the first roll
else if (sum == 2 || sum == 3 || sum == 12){
printf ("You rolled %d\n", sum);
printf ("You loss!\n");
printf ("Play again ? 'Y' or 'N'\n");
scanf ("%c", &command);
}
// condition for winning for the second roll
else if (sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
printf ("You rolled %d\n", sum);
printf ("Your point is %d\n", sum);
int sum1 = rand_num(); // request new random variable
while (sum1 != 7 && sum1 != sum){ //
printf ("You rolled %d", sum1);
int sum1 = rand_num (); // request new random variable
}
if (sum1 == 7)
printf ("You loss!\n");
else if (sum1 == sum){
printf ("You win!\n");
printf ("Play again ? 'Y' or 'N'\n");
scanf ("%c", &command);
}
}
}while (command == 'y' || command == 'Y');
}
【问题讨论】:
-
味道如何?
-
测试时
标签: c