Friday, July 31, 2009

Simple Caculator in C, What am i doing wrong?

#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





void addMe(int x, int y);


void subtractMe(int x, int y);


void multiplyMe(int x, int y);


void divideMe(int x, int y);


int main()


{


int x, y, ans, i;


int choice;


ans=0;





printf("Enter the first number --%26gt;\n");


scanf("%d",%26amp;x);





printf("Enter the second number --%26gt;\n");


scanf("%d",%26amp;y);





addMe(x, y);


subtractMe(x, y);


multiplyMe(x, y);


divideMe(x, y);





system("PAUSE");


return 0;


}//endmain





void addMe(int x, int y)


{


ans = x+y;


printf("First plus Second = %d\n", ans);





}//add


void subtractMe(int x, int y)


{


ans = x-y;


printf("First minus Second = %d\n", ans);





}//subtract


void multiplyMe(int x, int y)


{


ans = x*y;


printf("First times Second = %d\n", ans);





}//multiply


void divideMe(int x, int y)


{


ans = x/y;


printf("First divided by second = %d\n", ans);





}//divide

Simple Caculator in C, What am i doing wrong?
if u define int ans before the declaration of funtions as a global variable it works without the need of defining them in each function.
Reply:So, perhaps I am mistaken, since it has been a long time since I have programmed much of anything in a main loop, but why are you "declaring" ans in the main loop instead of as a variable within each function? Additionally, your problem is that you don't declare 'ans', you just set it equal to 0, you need to declare it as an int.
Reply:you can also try this approach


instead of doing this





void multiplyMe(int x, int y)


{


ans = x*y;


printf("First times Second = %d\n", ans);


}//multiply





try this


void multiplyMe(int x, int y)


{


printf("First times Second = %d\n", x*y);


}//multiply
Reply:I'm not seeing anything that is jumping out at me as being wrong. I see a couple of things you will need to do.





One, you need so data checks. You need to make sure that the data that a user enters is really a number. If someone enters two letters it would cause your program to crash when it tried to add.





Second, when you subtract. Are you allowed to get an answer that is negative? If so how are you handling printing the number as a negative? If you can't have negitive numbers you need to check before you subtract that x is larger than y.





Third, when you divide you need to make sure that y isn't zero. This will also cause your program to crash since you cannot divide by zero.





The above are a few improvements on your program. If you are getting a specific error when compiling or running the program post those errors here so we can know where to look for a problem.
Reply:Can you post the error message?


Your code looks ok to me.


then again, its been 8 years since ive written a C program.


No comments:

Post a Comment