Reputation: 23
I have a program for a basic calculator. It is supposed to add/subtract/multiply/divide. I can get it to perform one operation, but not consecutive ones. Any help?
I'm not really sure what function to use. I want it to do something repeatedly I should use a loop, right? but how?
Here is the code. thanks for the input!
#include <stdio.h>
int main ( void )
{ char op; double result = 0.0, num;
printf("The calculator is on.\nPerform an operation:0.0");
scanf("%c", &op);
while(op != result)
{
scanf("%lf", &num);
if( op=='+')
{result+=num;
printf("The new result is %6.2f", result);
}
else if(op=='-')
{result-=num;
printf("The new result is %6.2f", result);
}
else if(op=='*')
{result*=num;
printf("The new result is %6.2f", result);
}
else if(op=='/')
{result/=num;
printf("The new result is %6.2f", result);
}
else{
printf("Not an operation of the function.\nTry again.");
}
}
return 0;
}
Upvotes: 0
Views: 268
Reputation: 19494
while(op != result)
Is almost certainly wrong. This will terminate the loop whenever the result matches the ascii value of the operation. So if the result is 42 when multiplying, 43 when adding, 45 when subtracting, or 47 when dividing.
I think you should either pick a code for "quit", maybe 'q', and check for that in the loop.
while(op != 'q')
Or, check that the file has not reached EOF, otherwise quit. This is the usual strategy for shell programs of this sort.
Upvotes: 1