【问题标题】:My calculator ignores the scanf- function I use to read in a mathematical operator [duplicate]我的计算器忽略了我用来读取数学运算符的 scanf- 函数 [重复]
【发布时间】:2020-12-21 10:45:10
【问题描述】:

我尝试在C 中编写计算器,但程序忽略了我尝试从终端扫描出来的运算符(加号、分钟等)。

代码如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
float Zahl1;
float Zahl2;
float Ergebnis;
char Methode ="";


printf("Geben Sie bitte eine Zahl ein.\n");
scanf("%f", &Zahl1);
printf("Geben Sie bitte eine zweite Zahl ein.\n");
scanf("%f", &Zahl2);
printf("Geben Sie ein Verechnungszeichen ein.");
scanf("%c", &Methode);


if (Methode == '+') 
   Ergebnis= Zahl1 + Zahl2;

else if(Methode == '-') 
    Ergebnis= Zahl1 - Zahl2;

else if(Methode == '*') 
    Ergebnis= Zahl1 * Zahl2;

else if(Methode == '/') 
    Ergebnis= Zahl1 / Zahl2;

printf("%f", Ergebnis);

return 0;

}

终端:

Geben Sie bitte eine Zahl ein.
5
Geben Sie bitte eine zweite Zahl ein.
7
Geben Sie ein Verechnungszeichen ein.-25905410257214286834448728064.000000%

评论:我无法输入运算符并且数字自动出现。

【问题讨论】:

  • 使用 scanf(" %c", &c) ; & switch 语句检查字符 c 是否是除法、乘法、减法、加法而不是 if else 语句

标签: c scanf


【解决方案1】:

问题: 在前面输入操作数之后,按 ENTER 键,这会在输入缓冲区中留下一个换行符。其他格式说明符,如 %d%f 会忽略前导空格,但 %c 不会,并且空格(换行符)是有效的匹配项和输入。

解决方案:你需要改变

 scanf("%c", &Methode);

scanf(" %c", &Methode);
      ^^^

避免匹配输入缓冲区中已经存在的任何现有前导空白,正在扫描并被视为输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 2015-02-04
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多