gpt4 book ai didi

c - pig 游戏运行时错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:18 30 4
gpt4 key购买 nike

我在类里面被要求完成这个项目。任务是创建一个 pig 游戏,使用随机数生成器进行掷骰,并在总数达到 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;
}
}

最佳答案

您在 player1player2 函数中使用未初始化的 total。在各自的声明中初始化它们(即 int total = 0;)。

main 函数中的 score1score2 变量也是如此。

最后,您需要注意某些条件语句中的优先顺序,具体取决于您的预期行为。例如:

while (choice2 == 'y' || choice2 != 'y' && choice2 != 'n' || sum2 != 0)

||&& 哪个先应用?

关于c - pig 游戏运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482166/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com