计算器程序需要输入+和 - 两次

时间:2014-10-15 18:01:12

标签: c calculator

我正在编写一个简单的计算器程序来加,减,乘,除和做指数方程。程序必须重复,直到输入“q0”,它必须有两个函数,如我所写的主函数调用。问题是,当我运行程序时,第一个数字显示正常然后我可以乘法,除法,并且指数函数很好但是如果我想要加或减,我必须输入+或 - 两次才能计算它。这是我写的程序:

#include <stdio.h>
#include <math.h> 

void scan_data(char *oprter, double *oprand); 
void do_next_op(char oprter, double oprand, double *accum);

int 
main(void) 
{ 
  double nmber, /* input/output - operand */ 
         total; /* output - final result */ 
  char    sign; /* input/output - operator */ 

    total = 0;

    do {
        scan_data(&sign, &nmber);

        do_next_op(sign, nmber, &total);
    } while (sign != 'q');

    printf("Final result is %.2f", total);

  return (0); 
} 

/* 
 * Gathers operator and operand to perform calculation
 * Post: results are stored in cells pointed to by oprter, and oprand
 */ 
void 
scan_data(char *oprter, /* input - amount being withdrawn */ 
        double *oprand) /* output - number of tens */
{ 
    double amount;

    amount = 0;

    scanf("%c", &*oprter);
    scanf("%lf", &amount);

    *oprand = amount;
} 

/*
 * Performs calculation and displays results
 * Pre: oprter and oprand are defined
 * Post: function results are stored in cell pointed to by accum
 */

void
do_next_op(char oprter, 
         double oprand, 
          double *accum)
{
    double tot_amount;

    tot_amount = *accum;

    switch(oprter)
    {
        case '+':
            tot_amount = (tot_amount + oprand);
            printf("result so far is %.2f\n", tot_amount);
            break;
        case '-':
            tot_amount = (tot_amount - oprand);
            printf("result so far is %.2f\n", tot_amount);
            break;
        case '*':
            tot_amount = tot_amount * oprand;
            printf("result so far is %.2f\n", tot_amount);
            break;
        case '/':
            tot_amount = tot_amount / oprand;
            printf("result so far is %.2f\n", tot_amount);
            break; 
        case '^':
            tot_amount = pow(tot_amount, oprand);
            printf("result so far is %.2f\n", tot_amount);
            break;
    }

    *accum = tot_amount;

}

它正在做的一个例子如下:

5 到目前为止的结果是5.00

5

-5

++ 5

结果到目前为止是10.00

- 5

结果到目前为止是5.00

* 2

结果到目前为止是10.00

/ 2

结果到目前为止是5.00

^ 2

结果到目前为止是25.00

Q0

最终结果是25.00

1 个答案:

答案 0 :(得分:0)

问题很可能是scanf在执行

时将换行符留在输入缓冲区中
scanf("%lf", &amount);

这意味着下次调用

scanf("%c", oprter);

它将读取该换行符。

这可以通过让scanf通过向scanf格式字符串添加单个空格来读取和跳过所有前导空格来解决,例如

scanf(" %c", oprter);
//     ^
//     |
//     Note space here