我正在编写一个简单的计算器程序来加,减,乘,除和做指数方程。程序必须重复,直到输入“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