0
//calculate on interest rate
for(rate=0.05; rate <=0.1; rate++)
{

    amount = principal*pow(1+rate, year); 
    
    // output data
    printf("%0.2f $%8.2f\n", rate, amount);  
    
}

I'm supposed to show the interest rate from 5 percent to 10 percent for an outer loop. For some reason, it won't show from 0.05 to 0.10 as a result. When I change the numbers from 0.05 to 5 and 0.10 to 10. It works for me.

That gave me a hint that I cannot use decimal places for a loop. How can I fix that? I have to display as decimal places.

phuclv
  • 37,963
  • 15
  • 156
  • 475
blacklune
  • 43
  • 1
  • 7
  • Possible duplicate of [For loop with float as counter, increasing by 0.01, does not print expected float values](https://stackoverflow.com/questions/16124040/for-loop-with-float-as-counter-increasing-by-0-01-does-not-print-expected-floa) – phuclv Apr 04 '19 at 14:26
  • [Floating point inaccuracies](https://stackoverflow.com/q/4575643/995714), [Is floating point math broken?](https://stackoverflow.com/q/588004/995714) – phuclv Apr 04 '19 at 14:27

3 Answers3

1

You're incrementing rate by 1 (via rate++), but really you want to increment it by 0.01. Try this instead:

for(rate = 0.05f; rate <= 0.1f; rate += 0.01f)
{
  ...
}
Buddy
  • 10,874
  • 5
  • 41
  • 58
  • Oh, I never knew that. Thank you so much :) – blacklune Feb 19 '16 at 04:26
  • that would not solve the problem in every cases, it might not even work when float is not 32-bit IEEE-754 single precision – phuclv Feb 19 '16 at 04:47
  • @LưuVĩnhPhúc what are you talking about? C++ defines `float` as having ~7 digits of precision – Buddy Feb 19 '16 at 05:06
  • for example if the accumulator result is slightly larger than 0.1 then it'll stop at ~0.09. If exactly 6 loops is expected then floating-point math is not the way to go – phuclv Feb 19 '16 at 05:24
  • Yeah, perhaps it technically should be `rate <= 0.1f + FLT_EPSILON`, but I think this is close enough (pun intended) – Buddy Feb 19 '16 at 05:27
0

What do you think the ++ will do on a floating number? Plus 0.1, or 0.01, or 0.001? It adds ONE (1) to the number regardless of the type, e.g. int, float, double, etc.

user3207158
  • 619
  • 2
  • 5
  • 22
0

First, as others said, you're increasing the variable by 1.0 each loop. If you debug or print rate after the loop you'll see that immediately

However even if you change the loop to for(rate=0.05; rate <=0.1; rate += 0.01) it will still won't work properly because none of the negative powers of 10 are representable in binary floating-point

You must loop in integer by counting in the second decimal places then divide by 100 while calculating

for (rate = 5; rate <= 10; rate++)
{
    amount = principal * pow(1 + rate/100.0, year); 

    printf("%0.2f $%8.2f\n", rate/100.0, amount);
}
phuclv
  • 37,963
  • 15
  • 156
  • 475