tags:

views:

212

answers:

3

Trying to write out a simple C Calculator script, using only the basic +, -, /, *. I have the following but not sure why it's not printing correctly. Any experienced C users out there?

#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;
+16  A: 

You never print the result...

You need to add something like this:

printf("Result: %f", result);
Thomas Owens
+6  A: 

"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.

abelenky
I use this to test it and I'm not getting anything. Just 0.00000000 + 0.000000 = 0.000000000case '+': printf("Answer: %f + %f = %f \n", number1, number2, result); break;Sorry I am trying to understand ;(
Tater
Ah I see. thank you :) I see.
Tater
my above error in my code was making it not work with your example. However you were correct and I greatly appreciate your response.
Tater
For `double` types (such as number1 and number2), you need to use the `%lf` conversion specifier: `scanf("%lf %c %lf", `.
John Bode
why is %lf needed?
Tater
%f is for floats. %lf is for long-floats (aka. doubles).If you use floats, use %f. If you use doubles, use %lf.
abelenky
A: 
/* I think I see the problem; you're trying to reinvent the wheel. */
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    system("/bin/bc");
    return 0;
}
pbr
I do not understand.
Tater
Tater, there's a linux program out there called "bc" that's a really well implemented calculator program. The code above just runs it.My point is, you're travelling a coding path that's well-traveled already; you're reinventing the wheel. Sorry I wasn't clearer.
pbr
i think this was a learning exercise, not paving new roads ;)
dharga
Learning which tools/languages are best for solving particular problems is pretty important too.
pbr