I asked this question before now, when i first asked this question I didnt know what the problem was but I know and I have tried to read through Is floating-point math broken? and Why Are Floating Point Numbers Inaccurate? they showed the reason for the problems but I didn't really see anyway to bypass this problem in the code I have written so now I am asking if any body knows what I should do to the code to make the program work. The code and description below
The idea behind this program is for it to find the value of two doubles a
and t
, where if they were multiplied they give a specified value. So if the specified value was 4 the program has to find the values of a
and t
, where if they were multiplied it would give 4. The variable t
is in a range of 5 to 10.
I wrote the following code
int main(void)
{
double a = 0.01;
double t = 5;
while(1){
if(t * a != 4){
t = t + 0.01;
if(t > 10){
t = 5;
a = a + 0.01;
}
}
else if (t * a == 4){
break;
}
}
printf("%f %f", t, a);
return 0;
}
The code doesn't seem to work if I i try to increment the values using 0.01 although it works if the value of increment is 1. I know the reason this happens but how would I fix this in this program code or are there are other ways I could do write the code?. The code just seems to loop forever