C简介:加法和印刷

And*_* Hu 1 c printf calculator addition

我正在尝试制作一个可以执行各种算术功能的基本计算器,从添加开始!现在我已经得到了它的基本逻辑,但我不确定如何获取两个输入并打印出来!

#include <stdio.h>

int main()
{
    char mychar;
    int a;
    int op1;
    int op2;

    printf("Welcome to Andrew Hu's calculator program!\n"); //Greeting

    while(1)
    {    printf("Enter a mathematical operation to perform:\n");
        scanf("%c", &mychar);

    if(mychar == '+') //Valid Operators
        a = 1;
    else
        a = 0;


    if(a == 0) //Operator Checker, error if invalid
        printf("\nError, not a valid operator\n");
    else if(a == 1){
        printf("%c\n", &mychar),
        printf("Enter OP1:\n"),

       /* not sure what to put here to echo the character as a decimal*/

        printf("Enter OP2:\n"),

         /* not sure what to put here to echo the character as a decimal either*/

        printf("Result of %d %c %d = %d\n", op1, mychar, op2, (op1 + op2) )
        /* this last line I'm not too sure of. I'm trying to print out the expression
           which is op1 + op2 = the sum of both. */
              ;
    }
    }        
Run Code Online (Sandbox Code Playgroud)

San*_*Pai 5

使用scanf语句来获取输入,就像使用数学运算符一样.切换case语句可以很好地实现计算器.

scanf(" %d",&op1);
Run Code Online (Sandbox Code Playgroud)