gpt4 book ai didi

c - 警告 : statement with no effect [-Wunused-value] with if statements

转载 作者:行者123 更新时间:2023-11-30 14:37:18 26 4
gpt4 key购买 nike

所以我试图找出 while 循环和大多数 if 语句,所以我尝试制作这个小游戏,其中你有一定的生命值,怪物也有,只要你们都有超过 0 的生命值,循环就会运行,所以每个循环怪物都会对你造成 50 点伤害,但是使用 scanf 和 if 语句可以通过插入“2”来改变情况,你会减少你所受到的伤害,通过使用“3”你会增加你的生命值并使用“1"你对怪物造成了伤害,但由于某种原因,负责这些事件的 IF 语句似乎不起作用

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(){
int monsterhealth =100;
int health =100;
int damage =50;
while(health>0&&monsterhealth>0){
int action [10];
printf("player has %d health \n",health);
printf("monster has %d health\n",monsterhealth);
printf("act:attack[1]\ndefend[2]\npotion[3]\n");
scanf ("%d",action);
if(action==1){(monsterhealth==monsterhealth-40);}
else if(action==2){(damage==damage-30);}
else (action==3);{(health==health+100);};
health=health-damage;

}
}

最佳答案

关于:

int action [10];

如果您只需要一个操作,请声明一个简单的对象,而不是数组:

int action;

当您进行更改时,您将需要更改:

scanf ("%d",action);

至:

scanf("%d", &action);

action的地址传递给scanfscanf 需要知道 action 的地址,以便对其进行更改。如果您使用数组是因为 scanf 似乎不适用于简单对象,那么请不要这样做。数组可以解决您在使用 scanf 时可能遇到的问题,因为它们在 C 中具有某些行为,但这不是正确的解决方案。

关于:

while(health>0&&monsterhealth>0){

不要将代码挤在一起。写得容易阅读,并且间距能够传达含义:

while (health > 0 && monsterhealth > 0) {

关于:

(monsterhealth==monsterhealth-40);

该语句没有任何效果,因为 == 只是比较两个事物。该语句不会更改任何对象(变量)的值或具有任何其他可观察到的效果。它说“将 monsterhealthmonsterhealth-40 进行比较,然后对比较结果不执行任何操作。”这里你想要的是赋值运算符 = 而不是 ==,它表示“在这个东西中放入一个新值”:

monsterhealth = monsterhealth-40;

以类似方式更改要分配新值的其他语句。

关于:

else (action==3);{(health==health+100);};

多个if-else语句的形式为:

if (condition)
statement;
else if (condition)
statement;
else
statement;

请注意,它应该以else语句结束,而不是else(条件)语句。使用上面的行结构和缩进。 (有时,可以将带有单个 if 的非常短的语句放在同一行,但除非您更有经验并且具有良好的风格感,否则不要这样做。这大约需要三十年左右的时间开发。)您想要的代码是:

if (action == 1)
monsterhealth = monsterhealth - 40;
else if (action == 2)
damage = damage - 30;
else
health = health + 100;

有些人可能会用有关其所涵盖案例的信息来装饰else,例如:

if (action == 1)
monsterhealth = monsterhealth - 40;
else if (action == 2)
damage = damage - 30;
else /* action == 3 */
health = health + 100;

有些人主张将所有附加到 ifelse 语句的语句放在大括号中,以避免某些编辑错误。对于单个语句,C语言不需要它。

C 有另一种形式的语句,旨在处理您在这些 if 语句中测试的特定条件,即 switch 语句,但我认为您刚刚习惯这些语句,稍后将了解 switch

关于c - 警告 : statement with no effect [-Wunused-value] with if statements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429254/

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