gpt4 book ai didi

c - 如何在 C 中制作一个简单的计算器来保存中间结果

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:14 24 4
gpt4 key购买 nike

大家好!我正在解决 S.Kochan 的“C 编程”一书的练习部分中的一个问题,实际上陷入了这个问题,这建议在 C 中创建一个简单的计算器,它将中间结果保存在所谓的“累加器”中。因此,当您输入一个值,然后按“S”时 - 该值应该被保存,所有进一步的操作都应该使用该值执行。当你按下“E”时——程序应该结束,当你按下任何基本算术符号时,应该采取适当的行动等等。我正在使用永恒的 for 循环和 switch-case 运算符,但出了点问题。该值未正确显示< 算术运算也是如此。

这是我的代码

#include <stdio.h>

int main(void)
{
float accumulator, value;
char operator;

printf("Calculator\nType in your value:\n");
for(;;)
{
scanf("%f %c %f", &accumulator, &operator, &value);

switch(operator)
{
case 'S':
printf("=%.2f\n", accumulator);
break;
case 'E':
printf("=%.2f\nEnd of programm");
break;
case '+':
accumulator=accumulator+value;
printf("=%.2f", accumulator);
break;
case '-':
accumulator=accumulator-value;
printf("=%.2f", accumulator);
break;
case '*':
accumulator=accumulator*value;
printf("=%.2f", accumulator);
break;
case '/':
if(value==0)
printf("You can not divide by zero");
else
accumulator=accumulator/value;
printf("=%.2f", accumulator);

break;
default:
printf("Unknown symbol");
}
}
return 0;
}

我做错了什么?附言抱歉我的英语不好)

最佳答案

当你按下 E 时,使用 exit(0) 退出程序;而不是休息

 case 'E':
printf("End of programm");
exit(0);

在你的程序中,你使用累加器来存储中间结果,但你也在每次迭代中将其作为输入值,因此你可能会丢失保存先前操作结果的累加器的值,如果您只在循环之前扫描累加器值一次,然后在每次操作后使用累加器的值

为此你需要这样修改

scanf("%f", &accumulator );
for(;;)
{
scanf(" %c %f",&operator, &value);
...........

关于c - 如何在 C 中制作一个简单的计算器来保存中间结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644361/

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