gpt4 book ai didi

c - while 循环不会停止循环

转载 作者:行者123 更新时间:2023-11-30 19:15:24 25 4
gpt4 key购买 nike

我想我搞砸了,我的代码过度循环(它不会停止)。即使输入0后它也会继续循环。请指出我哪里做错了。

#include <stdio.h>

int main()
{
int day=1, exp=1, tallow;
float allow,tday,daily, texpen;

printf("\nDay %d allowance. [Type -1 to stop] --> ", day);
scanf("%f", &allow);

while(allow != -1){
printf("-- Expenses %d [type 0 to stop] ", exp);
scanf("%f", &daily);exp++;
while(daily == 0){
printf("\nDay %d allowance : %.2f", day, allow);
tday += daily;
printf("\nDay %d expenses : %.2f", day, tday);
break;
}
}

printf("\nTotal allowance for %d days : %.2f", day, tallow);
printf("\nTotal expenses for %d days : %.2f\n", day, texpen);

getch();
return 0;
}

当前输出:

Day 1 allowance. [Type -1 to stop] --> 20

-- Expenses 1 [type 0 to stop] 5

-- Expenses 2 [type 0 to stop] 3

-- Expenses 3 [type 0 to stop] 0

Day 1 allowance : 20.00

Day 1 expenses : 8.00 -- Expenses 4 [type 0 to stop]

如何摆脱“费用 4”?/如何在输入 0 后停止循环?

最佳答案

您可以更改您的

    while(daily == 0){

    if(daily == 0){

所以休息;将退出循环

    while(allow != -1){

然后不再打印“费用 4”。

并且您还需要将允许定义为 int,其中<​​/p>

scanf("%d", &allow);

应该是:

...
while(allow != -1){
printf("-- Expenses %d [type 0 to stop] ", exp);
scanf("%f", &daily);exp++;
tday += daily;
if(daily == 0){
printf("\nDay %d allowance : %.2f", day, allow);
printf("\nDay %d expenses : %.2f", day, tday);
break;
}
}

关于c - while 循环不会停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644295/

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