Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.3k views
in Technique[技术] by (71.8m points)

I am trying to create a simple calculator in C language that takes in 3 arguments in scanf. I cannot get the calculator working with float numbers

The calculator works as intended with everything but float numbers. I cannot comprehend how inputting different variables to "a" and "c" can throw me to a different part of the if-statement in this case. For example, inputting "2", then "+", then "3", and the calculator works perfectly giving "5.0" as output. However, when inputting "2.1", then "+", then "3.2", the output is "ERR". How is this possible and why is the output not 5.3?

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

int main() {
    
    float a;
    char b;
    float c;
    float res;
    
    char m1[2] = "-";
    char m2[2] = "+";
    char m3[2] = "*";
    char m4[2] = "/";

    scanf("%f %c %f", &a, &b, &c);

    if (strcmp(&b,m1) == 0) {
        res = a - c;
        printf("%.1f
", res);
    }
    else if (strcmp(&b,m2) == 0) {
        res = a + c;
        printf("%.1f
", res);
    }
    else if (strcmp(&b,m3) == 0) {
        res = a * c;
        printf("%.1f
", res);
    }
    else if (strcmp(&b,m4) == 0) {
        res = a / c;
        printf("%.1f
", res);
    }
    else {
        printf("ERR");

    return 0;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. strcmp can only be used to compare strings, you can't compare a string with a single character.

  2. There's lot of repetitive code.

  3. Variable names should be at least somewhat descriptive, e.g. op instead of b.

  4. You don't need to include <math.h>.

  5. You don't check the result of scanf and thus will attempt to use invalid values should it fail.

The program can be written this way:

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

int error(const char *msg) {
    fprintf(stderr, "%s
", msg);
    return EXIT_FAILURE;
}

int main() {
    float a, b, res;
    char op;
    
    if (scanf(" %f %c %f", &a, &op, &b) != 3)
        return error("Syntax error.");

    if (op == '-') res = a - b;
    else if (op == '+') res = a + b;
    else if (op == '*') res = a * b;
    else if (op == '/' && b) res = a + b;
    else
      return error("Invalid operator");

    printf("%.1f %c %.1f = %.1f
", a, op, b, res);
    return EXIT_SUCCESS;
}

You could also use %g instead of a fixed-precision %f format: the most appropriate representation will then be chosen automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...