【问题标题】:i cant find my mistake on my software (switch on C language) [duplicate]我在我的软件上找不到我的错误(打开 C 语言)[重复]
【发布时间】:2021-12-15 03:50:25
【问题描述】:

这是我在这里的第一篇文章。 我本月开始学习软件工程,我正在尝试使用 c 编写软件。 我找不到改变它的错误.. 谁能帮帮我!

    #include <stdio.h>
    void main()
    {
        int a,b,e;
        char operation;
        printf ("enter the first number:");
        scanf ("%d",&a);
        printf ("enter the second number:");
        scanf ("%d",&b);
        printf ("enter the operation:");
        scanf ("%c", &operation);
        switch (operation)
        {   case '+' :  e=a+b;
            break;
            case '-' :  e=a-b;
            break;
            case '*' :  e=a*b;
            break;
            case '/' :  e=a/b;
            break;
            default: printf("wrong choice!!");
    
        }

    printf("%d %c %d = %d \n", a, operation, b, e);
    }

【问题讨论】:

  • 您在尝试执行程序时收到什么错误?
  • 提示:检查c的值
  • C:\Users\JAOUADI\Desktop\C>最大输入第一个数字:5输入第二个数字:6输入操作:错误选择!!5 6 = 464950
  • 请使用tour 并阅读How to Ask。你的 questin 太让人猜不透了。它基本上是“嗨。代码”。

标签: c switch-statement


【解决方案1】:
#include <stdio.h>
    void main()
    {
        int a,b,e;
        char operation;
        printf ("enter the first number:");
        scanf ("%d",&a);
        printf ("enter the second number:");
        scanf ("%d",&b);
        getchar();
        printf ("enter the operation:");
        scanf ("%c", &operation);
        switch (operation)
        {   case '+' :  e=a+b;
            break;
            case '-' :  e=a-b;
            break;
            case '*' :  e=a*b;
            break;
            case '/' :  e=a/b;
            break;
            default: printf("wrong choice!!");
    
        }

    printf("%d %c %d = %d \n", a, operation, b, e);
    }

您的 scanf ("%c", &amp;operation); 正在从上述 scanf 语句中读取 换行符 \n。因此,要正确扫描操作语句,您必须添加检测 换行符 \ngetchar()

【讨论】:

  • 谢谢
【解决方案2】:

正如@Oka scanf() leaves the new line char in the buffer 已经提到的那样。

您必须丢弃换行符,您可以简单地在最后一个 scanf 之前使用 getchar() 函数来丢弃该单个字符(可能是换行符或不是换行符),以 100% 确定丢弃所有未读字符从输入缓冲区你可以做

while((c = getchar()) != '\n' && c != EOF)

否则可以使用" %c"(空格%c)忽略前导换行符。

【讨论】:

  • 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
相关资源
最近更新 更多