Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculator in C programming

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading