gpt4 book ai didi

c - 练习 #5 C 语言编程的第 6 章

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

Write a program that acts as a simple "printing" calculator. The program should allow the user to type in expressions of the form: number operator. The following operators should be recognized by the program: +, -, *, /, S. E

  • The S operator tells the program to set the "accumulator" to the typed-in number.
  • The E operator tells the program that execution is to end.The arithmetic operations are performed on the contents of the accumulator with the number that was keyed in acting as the second operand.

The following is a "sample run" showing how the program should operate:

Begin Calculations
10 S Set Accumulator to 10
= 10.000000 Contents of Accumulator
2 / Divide by 2
= 5.000000 Contents of Accumulator
55 - Subtract 55
-50.000000
100.25 S Set Accumulator to 100.25
= 100.250000
4 * Multiply by 4
= 401.000000
0 E End of program
= 401.000000
End of Calculations.

这是我的代码

#include <stdio.h>

int main(void)
{
char op;
float acc = 0, num;

printf("Begin Calculations\n");
while (op != 'E') {
scanf("%f %c", &num, &op);
switch (op) {
case '+':
acc += num;
printf("= %f\n", acc);
break;
case '-':
acc -= num;
printf("= %f\n", acc);
break;
case '*':
acc *= num;
printf("= %f\n", acc);
break;
case '/':
if (num == 0) {
printf("Division by zero\n");
}
else {
acc /= num;
printf("= %f\n", acc);
}
break;
case 'S':
acc = num;
printf("= %f\n", acc);
break;
case 'E':
printf("= %f\n", acc);
break;
default:
printf("Unknown operator\n");
break;
}
}
printf("End of Calculations");
}

我的代码与问题输入完美配合。但是,当我输入以下内容(和输出)时(与问题输入相同但“数字”和“运算符”之间没有空格):

Begin Calculations
10S
= 10.000000
2/
= 5.000000
55-
-50.000000
100.25S
= 100.250000
4*
= 401.000000
0E

当我输入 0E 时程序卡住了。我试图将 scanf("%f %c", &num, &op); 更改为 scanf("%f%c", &num, &op); 但它似乎没有解决我的问题。你能指出我的代码中的问题吗?请给我一个详细的解释,因为我是 C 的新手。在此先感谢您提供的任何帮助。

最佳答案

您正在读取一个浮点值。因此,如果 scanf 看到 0E,它会等待更多数字,因为它认为您输入的是指数,例如0E5(=0*10^5)。这就是为什么你的程序卡在这一点上的原因。我建议使用不同的字符来结束以避免这种歧义。

另一方面,如果 scanf 看到 0S,它将输出 0.0 作为浮点值和 'S' 作为字符,因为 'S' 永远不是浮点值的有效部分。

关于c - 练习 #5 C 语言编程的第 6 章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34737425/

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