gpt4 book ai didi

c - 一个简单的 “printing” 计算器

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:54 25 4
gpt4 key购买 nike

当我输入数字时,我看到输入数字 1输入运算符错误:未知运算符!累加器 = 0.000000输入数字

为什么步骤 - printf("Type in an operator ") 被跳过并替换为 - 默认值: printf ("错误:未知运算符(operator)!\n"); 休息;

提前感谢您的帮助!

// Program to produce a simple printing calculator

#include <stdio.h>
#include <stdbool.h>

int main (void)
{

double accumulator = 0.0, number; // The accumulator shall be 0 at startup
char operator;
bool isCalculating = true; // Set flag indicating that calculations are ongoing


printf("You can use 4 operator for arithmetic + - / *\n");
printf("To set accumulator to some number use operator S or s\n");
printf("To exit from this program use operator E or e\n");
printf ("Begin Calculations\n");

while (isCalculating) // The loop ends when operator is = 'E'
{

printf("Type in a digit ");
scanf ("%lf", &number); // Get input from the user.

printf("Type in an operator ");
scanf ("%c", &operator);
// The conditions and their associated calculations
switch (operator)
{
case '+':
accumulator += number;
break;
case '-':
accumulator -= number;
break;
case '*':
accumulator *= number;
break;
case '/':
if (number == 0)
printf ("ERROR: Division by 0 is not allowed!");
else
accumulator /= number;
break;
case 'S':
case 's':
accumulator = number;
break;
case 'E':
case 'e':
isCalculating = false;
break;
default:
printf ("ERROR: Unknown operator!\n");
break;
}

printf ("accumulator = %f\n", accumulator);
}
printf ("End of Calculations");

return 0;
}

最佳答案

char 的

scanf 消耗换行符。因此扫描的字符是“换行”而不是您期望的字符。

我替换了:

scanf ("%c", &operator);

通过

scanf ("%*c%c", &operator);

(使用 %*c 格式在运算符前消耗换行符)

并且您的代码运行良好。

关于c - 一个简单的 “printing” 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40961511/

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