-
program problem...
I have this small C program and I am unable to locate the mistake. Can someone help me locate it?
Code:
#include<stdio.h>
int main()
{
float a=0.0,b=0.0;
float a1=0.0;
a1=1.05;
b=0.05;
printf("\na1=%f\tb=%f\n",a1,b);
a=a1-1.0;
printf("\na=%f\tb=%f\n",a,b);
if(a<b)
printf("\nHELLO:b is greater than a\n");
else
printf("\ncondition is not satisfied");
printf("\n");
}
The program is supposed to print "Condition is not satisfired", but instead the program gives "HELLO:b is greater than a"
Hope someone can help me locate the error.
Thanks in advance.
-
You mean other than the fact that you forgot how to indent, and that you've neglected to pay attention to your compiler's warnings?
Quzah.
-
Oops.. sorry abt that...was in a hurry when I posted that. Will take care next time and indent.
There were no warning given by the compiler. I executed the program on Fedora 1 gcc compiler and there were no warnings or error messages.
-
Just a recommendation...
Code:
alias gcc="gcc -Wall -Wextra -ansi -pedantic"
-
> Hope someone can help me locate the error.
Yeah, your assumption that floating point numbers are totally accurate is the problem.
Mathematically, you expect a and b to be the same, but in floating point calculations, there is always a small degree of error.
So what you think might be a == b could result in any of these conditions being true
a < b
a == b
a > b
http://www.physics.ohio-state.edu/~d...point_math.pdf
-
Thanks Salem. It turns out that the assumption was only the problem. When I printed up to 20 digits after the decimal point, I could see the difference in the two numbers.