Tater
Tater

Reputation:

Creating a simple calculator in C

I am trying to write a simple C calculator script, using only the basic +, -, /, *. I have the following, but I'm not sure why it's not printing correctly.

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

int main (void)
{

    //introduce vars
    double number1, number2, result;
    char symbol; //the operator *, -, +, /

    //allow user interaction
    printf("Enter your formula \n");
    scanf("%f %c %f", &number1, &symbol, &number2);

    switch (symbol) {
        case '+':
            result = number1 + number2;
            break;
        default:
            printf("something else happened i am not aware of");
            break;
    }

    getchar();
    return 0;
}

Why is the result not being printed? Am I doing something wrong here,

result = number1 + number2;

Upvotes: 1

Views: 985

Answers (3)

pbr
pbr

Reputation: 480

/* I think I see the problem; you're trying to reinvent the wheel. */
#include &lt;stdio.h>
#include &lt;stdlib.h>

int main (void)
{
    system("/bin/bc");
    return 0;
}

Upvotes: 0

abelenky
abelenky

Reputation: 64682

"Why is the result not being printed?"

You calculate the answer properly, but do not print it anywhere.

You need to have something like:

printf("Answer: %f + %f = %f\n", number1, number2, result);

Without a print statement, nothing gets printed.


EDIT Responding to comment:

Did you do the printf after you calculate the result? Personally, I would put the printf just before the getchar();

For more debugging, just after your scanf, I would write:

printf("Input as received: number1 is %f\n number2 is %f\nsymbol is %c\n", number1, number2, symbol);

If that does not show the input that you typed, then something is wrong with how you gather input.

Upvotes: 6

Thomas Owens
Thomas Owens

Reputation: 116169

You never print the result...

You need to add something like this:

printf("Result: %f", result);

Upvotes: 17

Related Questions