A little help with this code?
Jeff15
Posts: 6
I am trying to make a simple calculator that displays the Sum, difference, product, and quotient of two variables typed into the terminal. For some reason, the product always displays NUM2 and DIF displays NUM1. Everything else reads zero. I am not sure what I am doing wrong. Any pointers will be appreciated
#include "simpletools.h"
int main(void)
{
int m = 0;
while(m <= 1)
{
char str [80];
float NUM1, NUM2, SUM, DIF, PRO, QUO;
pause(250);
print("I do basic calculations!\nType both numbers with a space in between them and hit Enter\n");
for( int n = 1; n <= 4; n++)
{
scanf("%f %f",&NUM1,&NUM2); //trying to get both inputs
pause(100);
SUM = NUM1 + NUM2 ; //reads 0
DIF = NUM1 - NUM2 ; //reads NUM2 but not the difference
PRO = NUM1 * NUM2 ; // reads NUM1
QUO = NUM1 / NUM2 ; // reads 0
print("%f SUM=%f \n DIF=%f \n PRO=%f \n QUO=%f \n");
print("all done\n Next Problem? Enter Numbers\n");
}
}
}
#include "simpletools.h"
int main(void)
{
int m = 0;
while(m <= 1)
{
char str [80];
float NUM1, NUM2, SUM, DIF, PRO, QUO;
pause(250);
print("I do basic calculations!\nType both numbers with a space in between them and hit Enter\n");
for( int n = 1; n <= 4; n++)
{
scanf("%f %f",&NUM1,&NUM2); //trying to get both inputs
pause(100);
SUM = NUM1 + NUM2 ; //reads 0
DIF = NUM1 - NUM2 ; //reads NUM2 but not the difference
PRO = NUM1 * NUM2 ; // reads NUM1
QUO = NUM1 / NUM2 ; // reads 0
print("%f SUM=%f \n DIF=%f \n PRO=%f \n QUO=%f \n");
print("all done\n Next Problem? Enter Numbers\n");
}
}
}
Comments
You aren't passing any variables to the print that prints the results. You need to pass SUM, DIF, PRO, and QUO.
Your current code prints NUM1 and NUM2 because, since you didn't specify which variables to print, "nearby" variables got printed, which in your case happened to be NUM1 and NUM2. If you got (un)lucky, you could have gotten all gibberish.
If you look at your compiler output, you'll see several warnings like this, one for each occurence: I'm pretty sure there are a number of other warnings you can get for doing things like passing print too many or not enough or wrongly typed arguments.
Note: to keep code formatting in this forum, select the code in the forum post editor and click on the "C" (code) icon...
OK, there are several issues with your code... You'll need to add the simple text library (#include "simple text.h") to your project for the print statements. The format for floats in print statements don't require but can be enhanced with a format such as: "%4.2f" rather than just "%f". And, your final formatted print statement did not include the variable names as arguments to the formatted output string. See the changes, below:
I also needed to add the -lm option to the Compiler Options find in SimpleIDE to get the scanf statements to work correctly. Without that option, the NUM1 & NUM2 variables were not getting updated by the scan statement.
dgately