1

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

#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. */
              ;
    }
    }        
4

2 回答 2

5

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

scanf(" %d",&op1);
于 2013-04-17T08:06:08.717 回答
2

使用该scanf函数读取浮点值,例如

double op1 = 0.0;
scanf("%lf", &op1);

表示将%lf输入的值读取为 -float值。

当您在命令行上输入值时,它们将被显示。

else if(a == 1){
    printf("%c\n", mychar), // don't use & with printf as it will print the address of mychar
    printf("Enter OP1:\n"),

   double op1 = 0.0;
   scanf("%lf", &op1);

    printf("Enter OP2:\n"),

    double op2 = 0.0;
    scanf("%lf", &op2);

    if(a == 1)
        printf("Result of %lf + %lf = %lf\n", op1, op2, (op1 + op2) );
        }
于 2013-04-17T08:03:55.393 回答