I have written the following for loop to demonstrate ceil() function of <cmath>.

for (double ceilDemo = 2.0; ceilDemo <= 3.0; ceilDemo += 0.1)
		cout << setw(10) << ceilDemo << setw(20) << ceil( ceilDemo ) << endl;

The output is as expected except for the last iteration. I mean in the first iteration, when the value of ceilDemo variable is 2.0, ceil() returns 2. for all next iterations upto 2.9 it gives 3 which perfect. Then two strange things happen.

  1. The loop terminates one iteration before I am expecting it to. I mean for the code I have given above, I get output only upto the value 2.9 of the variable ceilDemo.
  2. If I modify the loop termination condition to get one extra iteration then regardless of the fact that ceilDemo contains only 3.0, ceil() now returns 4.

Is it a problem due to using a variable of type double to control the loop or something else? Please reply!!!

Thanks in advance!

5 Years
Discussion Span
Last Post by Muhammad Anas

Because of how double's are represented (wikipedia has a good article) you are overshooting 3.0 enough that the loop appears to terminate prematurely. Try changing

ceilDemo += 0.1


ceilDemo += 0.01

You will see the results you expect, but of course more output.


Hummm, Thank you very much.

ceilDemo += 0.01;

really solved the problem but also as mentioned by you, the output is just too much for such a simple demonstration purpose.

Actually I was doing exercises of a C++ programming book where a question asks to write a program that will print argument/return value tables of about 12 math library functions. There is no restriction on producing the argument values at runtime. So, I think it would be better to manually call each function 4-5 times with different arguments in the program. However, It would require much more work on my part ... :(

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.