gpt4 book ai didi

c - 为什么我的 C 程序在使用 for 循环时只产生零答案?

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

我尝试使用for循环计算键入的书籍数量并总结它们的总价格,但最终我在C程序中只得到零价格。我的问题是什么?怎么解决?

 #include<stdio.h>     

int main(void)
{
int booknum;
float bookfee,bookgst,nogst,totfee,newfee,newfee_nogst;
bookgst=0.0;
nogst=0.0;
int cnt;
char code;
printf("Key in total books purchased >> ");
scanf("%d",&booknum);

for(cnt=1;cnt<=booknum;cnt++)
{
printf("\n\n");
printf("Key in price of the book >> ");
scanf("%f",&bookfee);
printf("Key in type( S=standard gst,Z=zero gst) \n>> ");
scanf("%c",&code);
getchar();
if(code=='S')
{
newfee=bookfee+0.6;
}
else if(code=='Z')
{
newfee_nogst=bookfee;
}
bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;
printf("\n");

}
totfee=bookgst+nogst;
printf("Book purchased with GST : RM %.2f\n",bookgst);
printf("Book purchased without GST : RM %.2f\n",nogst);
printf("Total payment : RM %.2f\n",totfee);

return 0;
}

最佳答案

这段代码有一些问题,但你已经快成功了!

第一code读书需要吃饭前\n ( see this ),否则代码既不是 Z不是S (这是一个换行符),这就是为什么从不添加费用的原因。(另搜索“fgets vs scanf”以了解如何使用更安全的 fgets )。

scanf(" %c",&code);

然后这些行

bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;

添加 newfee/newfee_nogst ;这些变量设置为0在循环之前,但在下一次出现时,它们仍然设置为前一次出现的值,因此可以将它们设置为 0在循环开始处,或者直接在 if 中添加值(见下文)。既然我们在这里,如果代码错误,则打印一个错误(在本例中,可能将 cnt 减一,以使用正确的代码再执行一次循环)。

此外,GST 计算可能是错误的,x 的 6% 是 0.06 * x ,如果您希望将 GST 添加到 x * 1.06 的值中

if(code=='S')
{
bookgst = bookgst + bookfee*1.06; // or bookgst += bookfee*1.06
}
else if(code=='Z')
{
nogst = nogst + bookfee; // or nogst += bookfee
}
else {
printf("Code not understood\n");
}

关于c - 为什么我的 C 程序在使用 for 循环时只产生零答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484040/

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