Page 1 of 1

Calculator bug

Posted: Mon Jul 28, 2003 3:41 pm
by Kon-Tiki
Got a bug in my calculator that I can't sort out. It does everything just fine, but using numbers that start with 0, (or 0. , tried both), will ignore the things after the ,.
Here's the code:

Code: Select all

#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

float calculate(float number1, char thingy, float number2) {
 float ans;
 switch (thingy) {
   case '+':
     ans = number1+number2;
     break;
   case '-':
     ans = number1-number2;
     break;
   case '*':
     ans = number1*number2;
     break;
   case '/':
     ans = number1/number2;
     break;
   case '#':
     ans = pow(number1, 1/(float)number2);
     break;
   case '^':
     ans = pow(number1,number2);
     break;
   default:
     break;
 }
 return ans;
}

int main()
{
   int number1;
   int number2;
    float ans;
   char thingy;

printf ("Enter the first number: ");
scanf("%d", &number1);
fflush(stdin);
printf ("Enter the operation to perform: +, -, *, / or # : ");
scanf("%c", &thingy);
fflush(stdin);
printf("Enter the second number: ");
scanf("%d", &number2);

ans = calculate(number1,thingy,number2);

FILE* fp;
fp = fopen("calc.txt", "a+");
fopen;
printf("%d%c%d=%f\n", number1, thingy, number2, ans);
fprintf(fp, "%d%c%d=%f\n", number1, thingy, number2, ans);
system("pause");
}
This thing compiles, which makes it even harder for me to pinpoint where the bug is.

-Kon-Tiki-

Re:Calculator bug

Posted: Mon Jul 28, 2003 5:30 pm
by Tim
Try using float and %f instead of int and %d. ints can't represent floating-point numbers.

Re:Calculator bug

Posted: Tue Jul 29, 2003 8:19 am
by Kon-Tiki
* Slaps against forehead *
It works now. Should've known it, since Anubis has explained the difference between floats and ints a couple of times. Thanks Tim.

-Kon-Tiki-

Re:Calculator bug

Posted: Wed Jul 30, 2003 4:53 am
by distantvoices
no... not against the forehead. this slows down thinking. better you slap on the backhead. Then the thoughts get speeeeed. *rofl*

Did I say already that I am in a queer mood today? ;D