Calculator bug

Programming, for all ages and all languages.
Post Reply
Kon-Tiki

Calculator bug

Post 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-
Tim

Re:Calculator bug

Post by Tim »

Try using float and %f instead of int and %d. ints can't represent floating-point numbers.
Kon-Tiki

Re:Calculator bug

Post 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-
distantvoices
Member
Member
Posts: 1600
Joined: Wed Oct 18, 2006 11:59 am
Location: Vienna/Austria
Contact:

Re:Calculator bug

Post 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
... the osdever formerly known as beyond infinity ...
BlueillusionOS iso image
Post Reply