gpt4 book ai didi

c - 《C 语言编程》第 6 章练习 #5, "simple “printing” 计算器”

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

C 语言编程第 6 章中的练习 #5,作者:Kochan

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.

Make certain that the program detects division by zero and also checks for unknown operators.

如果我输入 * 2,它会返回 inf。这就是我所做的:

#include <stdio.h>

int main(void)
{
float number1, number2;
char operator;

do
{
printf("Enter your number with S sign that set it as your accumulator \n");
scanf("%f %c", &number1, &operator);

} while (operator != 'S');


do
{
printf("Enter your expression with the correct format\n");
scanf("%f %c", &number2, &operator);

if ( operator == '+' || operator == '-' || operator == '/' || operator == '*')
{
switch (operator)
{
case '+':
number1 = number1 + number2;
printf("=%.6f\n", number1);
break;
case '-':
number1 = number1 - number2;
printf("=%.6f\n", number1);
break;
case '*':
number1 = number1 * number2;
printf("=%.6f\n", number1);
break;
case '/':
if( number2 == 0)
printf("Division by Zero\n");
else
{
number1 = number1 / number2;
printf("%.6f\n", number1);
}
break;
default:
printf("not a valid operator\n");
break;
}
}
else
printf("Retry.\n");

} while (operator != 'E');



printf("End of Calculations\n");
return 0;

}

最佳答案

对于 scanf("%f %c", &number2, &operator); 语句,* 不是 %f 的有效字符。 scanf 失败,但 do block 一次又一次地尝试将 * 读入 %f

将语句替换为

if ( ( scanf("%f %c", &number2, &operator)) != 2) {
number2 = 1.0f;
operator = 0;
scanf ( "%*[^\n]");
}

scanf 将返回成功读取的项目数。如果 scanf 不返回 2,则将值设置为某个适当的值,scanf ( "%*[^\n]); 将读取并丢弃缓冲区中不是换行符的所有内容。< br/>对 number1

的第一次扫描执行类似的操作

关于c - 《C 语言编程》第 6 章练习 #5, "simple “printing” 计算器”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294271/

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