我在课堂上得到了这个项目。任务是创建一个使用随机数生成器进行骰子掷骰的猪游戏,并在达到总数100时声明获胜者。我得到了“致命的运行时错误”,但由于我正在使用的编译器,我无法提供有关错误的更多信息。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* The diceroll function generates random numbers between 1 and 6 */
int diceroll (void) {
int num = (rand() % 6) + 1;
return num;
}
int player1 (void) { /* Function that handles the number generated by the diceroll func and returns number to main */
int dice;
int total;
dice = diceroll();
if (dice != 1) {
total = total + dice;
printf("you have rolled %d and your total is now %d \n", &dice, &total);
} else {
total = 0;
printf("You have rolled a 1, your total for this turn has been reduced to 0 \n");
}
}
int player2 (void) { /* Copy of player1 func with change of numbers */
int dice;
int total;
dice = diceroll();
if (dice != 1) {
total = total + dice;
printf("you have rolled %d and your total is now %d \n", &dice, &total);
} else {
total = 0;
printf("You have rolled a 1, your total for this turn has been reduced to 0 \n");
}
return total;
}
int main (void) {
int score1;
int score2;
char choice1;
char choice2;
int sum1;
int sum2;
while (score1 < 100 && score2 < 100) { /* Loop that runs until a player has won */
do {
printf("Player 1 do you want to roll y/n? \n");
scanf(" %c ", &choice1);
if (choice1 == 'y') {
sum1 = sum1 + player1();
score1 = sum1;
printf("Your score is %d \n", &score1);
} else if (choice1 == 'n') {
score1 + 0;
sum1 = 0;
printf("Your score is %d \n", &score1);
} else {
printf("invalid, repeat");
}
} while (choice1 == 'y' || choice1 != 'y' && choice1 != 'n' || sum1 != 0);
do {
printf("Player 2 do you want to roll y/n? \n");
scanf(" %c ", &choice2);
if (choice2 == 'y') {
sum2 = sum2 + player2();
score2 = sum2;
printf("Your score is %d \n", &score2);
} else if (choice2 == 'n') {
score2 + 0;
sum2 = 0;
printf("Your score is %d \n", &score2);
} else {
printf("invalid, repeat");
}
} while (choice2 == 'y' || choice2 != 'y' && choice2 != 'n' || sum2 != 0);
}
/* When a player has won, 1 of the following statements is displayed */
if (score1 >= 100 && score2 < 100) {
printf("Congrats player 1");
} else if (score2 >= 100 && score1 < 100) {
printf("Congrats player 2");
} else {
return 0;
}
}
答案 0 :(得分:1)
您在total
和player1
函数中使用player2
未初始化。在各自的声明中初始化它们(即int total = 0;
)。
score1
函数中的score2
和main
变量也是如此。
最后,根据您的预期行为,您需要注意某些条件中的优先顺序。例如:
while (choice2 == 'y' || choice2 != 'y' && choice2 != 'n' || sum2 != 0)
首先应用||
或&&
?
答案 1 :(得分:1)
这就是我所看到的:
player1
最后没有return total
声明main
中,score1
,score2
,sum1
和sum2
应初始化为0. printf
来电中,传递变量本身,而不是其地址,即不要使用&
。这可能是导致崩溃的原因。player1
和player2
可能应该total
作为函数的参数而不是局部变量。您需要分别传递sum1
和sum2
。根据操作顺序,如果您想要明确,do .. while
条件会如下所示:
((choice1 == 'y') || ((choice1 != 'y') && (choice1 != 'n')) || (sum1 != 0))
我认为这是你的意图,但最好还是添加括号,以便更清楚。