让用户在C中输入算术表达式

时间:2015-09-24 17:43:12

标签: c

我是大学新生,完全是编程新手。我必须写一个简短的程序,用户输入两个操作数,输入一个特定的精度(比如4个小数点),然后输入一个运算符,如/,+或*。然后计算表达式。

#include <stdio.h>

int main(int argc, const char * argv[]) {
int precision;
double a, b;
printf("Please enter desired precision");
scanf("%d", &precision);
printf("Please enter desired operands");
scanf("%lf %lf", &a, &b);
printf("%.*lf %.*lf", precision, a, precision, b);
printf("Please enter an expression\n");


return 0;
}

这就是我到目前为止所拥有的。不确定如何让用户输入运算符而不会出现错误。

1 个答案:

答案 0 :(得分:2)

您可以为运营商使用char类型,请注意" %c"格式的空格。这将清除任何前面的空格,例如在前一个输入之后输入缓冲区中留下的newline,否则将被接受为char

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

void fatal(char *msg) {
    printf("\n%s\n", msg);
    exit (1);
}

int main(int argc, const char * argv[]) {
    int precision;
    double a, b;
    char operator;

    printf("Please enter desired precision ");
    if (scanf("%d", &precision) != 1)
        fatal("Illegal precision entered");

    printf("Please enter desired operands ");
    if (scanf("%lf %lf", &a, &b) != 2)
        fatal("Illegal operands entered");

    printf("Please enter the operator ");
    if (scanf(" %c", &operator) != 1)
        fatal("Illegal operator entered");

    switch(operator) {
        case '+': 
            printf("%.*f %c %.*f = %.*f",
                   precision, a, operator, precision, b, precision, a + b);
            break;
        case '-': 
            printf("%.*f %c %.*f = %.*f",
                   precision, a, operator, precision, b, precision, a - b);
            break;
        case '*': 
            printf("%.*f %c %.*f = %.*f",
                   precision, a, operator, precision, b, precision, a * b);
            break;
        case '/': 
            if (fabs(b) > 0.0)
                printf("%.*f %c %.*f = %.*f",
                   precision, a, operator, precision, b, precision, a / b);
            else
                fatal("Divide by zero");
            break;
        default:
            fatal("Illegal operator");
    }
    return 0;
}