【发布时间】:2015-06-21 11:21:05
【问题描述】:
基本上我应该模拟一个掷三个骰子的程序,把它加起来。然后我会让用户猜测下一个滚动是更高、更低、相同还是他们只是想退出。我有两个问题。
这些数字不是随机的,显然这是我的一个大错误,但我似乎无法弄清楚。我在想我不需要第二个包含 3 个骰子对吗?反正他们一点帮助都没有。
无论如何,我的程序会同时执行所有 if/else if 语句。显然我不希望这种情况发生。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int diceOne, diceTwo, diceThree, diceSum=0, timesCorrect=0, choice;
int newDiceOne, newDiceTwo, newDiceThree, newDiceSum;
srand( time(NULL) );
diceOne = rand() % 6 + 1;
diceTwo = rand() % 6 + 1;
diceThree = rand() % 6 + 1;
newDiceOne = rand() % 6 + 1;
newDiceTwo = rand() % 6 + 1;
newDiceThree = rand() % 6 + 1;
printf("The three dice rolls: %d, %d, %d", diceOne, diceTwo, diceThree);
diceSum = diceOne + diceTwo + diceThree;
printf("\nTotal sum of dice is %d\n", diceSum);
do {
printf("Guess higher(1), lower(2), same(3) or quit?(4)\n");
printf(" You have been correct %d times\n", timesCorrect);
scanf("%d", &choice);
printf("The three dice rolls: %d, %d, %d", newDiceOne, newDiceTwo, newDiceThree);
newDiceSum= newDiceOne + newDiceTwo + newDiceThree;
printf("\nTotal sum of dice is %d\n", newDiceSum);
if (choice == 1)
{
if (newDiceSum > diceSum);
timesCorrect++;
printf("You are correct!\n");
}
else if (newDiceSum < diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 2)
{
if (newDiceSum < diceSum);
timesCorrect++;
printf("You are correct!\n");
}
else if (newDiceSum > diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 3)
{
if (newDiceSum == diceSum);
timesCorrect ++;
printf("You are correct!\n");
}
else if (newDiceSum != diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 4)
{
printf("Thanks for playing!!!!!!\n");
system("pause");
return 0;
}
} while (choice!= 4 );
}
【问题讨论】:
-
请缩进你的代码,不要学习任何使用
system("pause");的东西,如果它在你的教科书中,那么请放弃它,如果你的老师使用它,那就换你的老师。跨度> -
你在哪里掷骰子?不在循环中
-
请注意,数字不会均匀分布,因为
rand()很可能会返回模 2**n 的值。 -
我觉得练习就够了
-
为了清晰和简单的文档以及让我们人类更容易阅读代码,每个语句只声明一个变量。