Home > Net >  Calculator in C programming
Calculator in C programming

Time:04-14

This is the code for simple calculator in C and I implement on Visual Studio Code:

#include<stdio.h>

int main(){
    char opr;
    double fnum,snum;
    printf("Choose operation [A( ),B(-),C(*),D(/)]: ");
    scanf("%c",&opr);

    printf("Two numbers: ");
    scanf("%f %f",&fnum,&snum);

    switch (opr)
    {
    case 'A':
        printf("%lf   %lf = %lf",fnum,snum,fnum snum);
        break;

    case 'B':
        printf("%lf - %lf = %lf",fnum,snum,fnum-snum);
        break;

    case 'C':
        printf("%lf * %lf = %lf",fnum,snum,fnum*snum);
        break; 
        
    case 'D':
        printf("%lf / %lf = %lf",fnum,snum,fnum/snum);
        break;
    
    default:
        printf("Invalid Operator");
    }

    return 0;

}

When I run it, I got these output. I choose the operation as A and two numbers as 20 and 10, but it gives 0. 0.=0. as an output instead of giving 20. 10.=30. I cannot find why, thanks.

Choose operation [A( ),B(-),C(*),D(/)]: A
Two numbers: 20 10
0.000000   0.000000 = 0.000000

CodePudding user response:

The format string to scanf is incorrect. You have %f to read a float but you need %lf to read a double.

  •  Tags:  
  • c
  • Related