-
Calculator
Hey I started using this site to learn C yesterday, and I got to the chapter on functions and decided to try and make a little program to do simple calculations.
This is the what I've written so far;
Code:
#include <stdio.h>
int calc ( int x, int y );
int main()
{
int x;
char f;
int y;
printf( "Please input a number: " );
scanf( "%d", &x );
printf("Please choose a function(add, subtract, divide, or multiply):");
scanf("%c", f );
printf( "Please input a second number: " );
scanf( "%d", &y );
if (f == *);
{
printf( "The product of your two numbers is %d\n", mult( x, y ) );
}
else if (f == +);
{
printf( "The product of your two numbers is %d\n", add( x, y ) );
}
else if (f == /);
{
printf( "The product of your two numbers is %d\n", divide( x, y ) );
}
else (f == -);
{
printf( "The product of your two numbers is %d\n", subtract( x, y ) );
}
getchar();
}
int mult (int x, int y)
{
return x * y;
}
int add (int x, int y)
{
return x + y;
}
int subtract (int x, int y)
{
return x - y;
}
int divide (int x, int y)
{
return x / y;
}
However I can't seem to make it work, I get an error on the lines with the if statements saying; "syntax error before ')' token.
Can anyone help? Thanks
-
if (f == *);
'*' - to specify the literal constant
and the ; at the end should be removed
scanf("%c", f );
this line also has problems
-
thanks, that worked, but now i have a new problem lol, subtracting works fine, but if i try adding it just subtracts, and if i enter the * or / keys it automatically skips the option of adding a second number.
-
All your char operators, need that same 'char_here', treatment. Just to expand on Vart's good eye, here.
if(f == '-')
is not the same thing as
if(f == -)
at all.
-
> scanf("%c", f );
What is missing here, compared to your other scanf calls?
Also note that %c does NOT skip white space unlike all the other simple scanf formats.
So 3+2
would be different from 3 +2
Which compiler are you using?
-
should be an else-if and without the terminating semicolon else (f == -);
-
For clarity of code, "Self documenting" code I would replace:
1. variable f to be operator
2. You can use if statements here, as you have a short conditional list, but a switch/case statement would be preferred.
3. As mentioned all your "operators" should be wrapped within single quotes.