c-if-else比较器中布尔变量的问题



我正在尝试在我的游戏中制作一个升级系统。我使用3个布尔变量(用于3种不同的武器(。我在制作一个if-else比较器时遇到了困难,该比较器将查看哪些布尔变量是真/假(你有哪些武器,没有(,并将你带到适当的战斗场景中。if-else比较器不起作用,不管你有什么武器。它自动转到";否则";陈述的一部分(如果你没有武器,你会去哪里(。我包含了一个简化版本,只有一个bool变量。请帮忙。

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice;
int choice2;
bool weapon1 = false;

start:
printf("Where would you like to go? 1. Store  2. Arena: ");
scanf("%d", &choice);
if (choice == 1) {
printf("You got weapon1 from the store n");
bool weapon1 = true;
goto start;
}
else if (choice == 2) {
printf("You went to the arenan");
if (weapon1) {
printf("You won the battle because you had a weaponn");
exit(0);
}
else {
printf("You lost the battle because you did not have a weaponn");
exit(0);
}
}

return 0;
}

在与if (choice == 1)关联的大括号内写入bool weapon1 = true;定义了一个与早期weapon1无关的新weapon1

将其更改为weapon1 = true;,这将分配给早期的weapon1,而不定义新的weapon1

打开编译器中的所有或大多数警告消息,并注意它们。

问题在于重新初始化武器布尔变量。正确的代码是:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int choice;
int choice2;
bool weapon1 = false;
start:
printf("Where would you like to go? 1. Store  2. Arena: ");
scanf("%d", & choice);
if (choice == 1) {
printf("You got weapon1 from the store n");
weapon1 = true;
goto start;
} else if (choice == 2) {
printf("You went to the arenan");
if (weapon1) {
printf("You won the battle because you had a weaponn");
exit(0);
} else {
printf("You lost the battle because you did not have a weaponn");
exit(0);
}
}
return 0;
}

在C中使用goto(除了一些例外,直到函数的末尾(被认为是一种可怕的做法

定义变量后,不应在赋值开始时将其类型用作新定义。bool weapon1 = true;代替weapon1 = true;

#include <stdbool.h>
#include <stdio.h>
int main() 
{
int choice;
int choice2;
bool weapon1 = false;
bool endgame = false;
do
{
printf("Where would you like to go? 1. Store  2. Arena: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("You got weapon1 from the store n");
weapon1 = true;
break;
case 2:
if (weapon1) printf("You won the battle because you had a weaponn");
else  printf("You lost the battle because you did not have a weaponn");
endgame = true;
break;
default: 
break;                
}
}while(!endgame);
}

最新更新