0

I want someone to run the code, you will find that the code at line number 14 to 17, I don't what this error is. I am giving my code along with this error image.

enter image description here

/*
    A simple calculator made with if-else and switch case
*/

#include <stdio.h>

int main() {
    // if-else
    
    char _opt_1;
    float x_1, x_2;
    
    printf("Enter a valid operator from (+ , - , * , /:  ");
    scanf("%c", &_opt_1);
    
    printf("Enter first number: ");
    scanf("%f", &x_1);
    printf("Enter second number: ");
    scanf("%f", &x_2);
    
    if(_opt_1=='+') {
        printf("The sum is: %f \n", x_1+x_2);
    }else if(_opt_1=='-') {
        printf("The sum is: %f \n", x_1-x_2);
    }else if(_opt_1=='*') {
        printf("The sum is: %f \n", x_1*x_2);
    }else if(_opt_1=='/') {
        printf("The sum is: %f \n", x_1/x_2);
    }else{
        printf("Please enter a valid operator \n");
    }
    
    // switch case
    char operator;
    float x, y;
    
    printf("Enter the operation you want to perform like (+,-,*,/): ");
    scanf("%c", &operator);
    
    printf("Enter the first number: ");
    scanf("%f", &x);
    printf("Enter the second number: ");
    scanf("%f", &y);
    
    switch(operator) {
        case '+':
            printf("The sum is: %f", x + y);
            break;
        case '-':
            printf("The difference is: %f", x - y);
            break;
        case '*':
            printf("The product is: %f", x * y);
            break;
        case '/':
            printf("The division is: %f", x / y);
            break;
        
        default:
            printf("Please enter a valid operator");
    }
    
    return 0;
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
dev op
  • 13
  • 4
  • What is the error you are talking about? Please also add text output as formatted text, not as an image. – Gerhardh Jul 26 '22 at 07:30
  • All four operations in the if/else version say "sum"... Too much copy/paste! (And, here's a tip: check if 'x_2' is equal to 0 before asking the math library to perform an illegal operation... Check in both your versions...) – Fe2O3 Jul 26 '22 at 07:32
  • Try `scanf(" %c", &operator);` Note the extra space. – Gerhardh Jul 26 '22 at 07:36
  • @Gerhardh yes this worked thanks, can you please tell what happens by this extra space, any online docs about this. – dev op Jul 26 '22 at 07:39
  • The documents are basically the C standard or any manpage for `scanf`. Also the linked question provides explanation for this behaviour: Any whitespace (space, newline, etc.) is simply skipped. – Gerhardh Jul 26 '22 at 07:42

0 Answers0