简体   繁体   English

C程序基本计算器

[英]C program basic calculator

#include<stdio.h>
int main()
{
    int a,b;
    char op;
    scanf("%d",&a);
    scanf("%c",&op);
    scanf("%d",&b);
    int w,x;
    w=a+b;
    x=a-b;

    switch(op)
    {
        case'+':
        {
            printf("%d",w);
            break;
        }
        case'-':
        {
            printf("%d",x);
            break;
        }
        default:
        {
            printf("Invalid");
            break;
        }
    }
    return 0;
}

Every time I enter the second input – the character(+ or -) – it directly goes to invalid in the switch case. 每当我输入第二个输入-字符(+或-)时,在切换的情况下,它直接变为无效。 What am I doing wrong here? 我在这里做错了什么?

Your scanf sequence isn't doing what you think it is. 您的scanf序列没有按照您的想象做。 Print out the value of op before the switch and you'll see the problem. switch之前打印出op的值,您会发现问题所在。

Your program works just fine. 您的程序运行正常。 Your problem is with the input: use 123+456 instead of pressing enter between the decimal and the operator. 您的问题在于输入:使用123+456而不是在小数点和运算符之间按Enter。

Here is an example of your program: 这是您的程序的示例:

$ ./basic 
456-123
333$ 

I suggest adding \\n to each printf() format string to eliminate the prompt displaying in the same line. 我建议在每个printf()格式字符串中添加\\n以消除在同一行中显示的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM