gpt4 book ai didi

c - while 循环无法检测简单的数学运算

转载 作者:行者123 更新时间:2023-11-30 19:01:49 26 4
gpt4 key购买 nike

我试图了解 while 循环的工作原理以及如何使用它们,因此我尝试创建一个循环,其中代码从名为 health 的变量中删除 50 个点,直到变量 = 0,但由于某种原因它无法检测到删除点数的操作,因此它只会继续打印“玩家有 100 生命值”。

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

int main()
{
/*this is me just messing around and learning*/;
int health=100;
while (health>0)
printf("player has %d HP\n",health);
health=health-50;
printf("player took -50 damage ");
printf("player has %d HP\n",health);
if(health<20)
(printf("low on health?"));
else
printf("that will leave a mark");
return 0;
}

最佳答案

您需要使用大括号来确定属于 while 循环的代码范围。您可能打算这样做:

while (health > 0) {
printf("player has %d HP\n", health);
health = health - 50;
printf("player took -50 damage ");
printf("player has %d HP\n", health);
if (health < 20) (printf("low on health?"));
else printf("that will leave a mark");
}

您当前的代码,就目前而言,将无限循环,打印 player has 100 health,因为 while 循环的主体只是默认 printf 语句紧邻下一行。

关于c - while 循环无法检测简单的数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57213239/

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