### A strange thing about for-loop

Hi, everyone,I have a question about for-loop .Here is simplified question.

Output result for clip1 is 0.9 ,and for clip2 is 0.7 ?
Does it means 0.8<0.8 but 0.7!<0.7 for C++ ?
How strange it is!

 ``1234567891011121314151617181920`` `````` //clip1 void main(){ int i; double x(0),h(0.1); for(i=1;x<0.8;i++){ x=x+h; } cout<
This is very strange (I tried it myself also), but I would personally use while loops for this since the int i isn't really necessary for the program.
You shouldn't use FP values (floats & doubles ) in loop conditions. They are stored as binary fractions and cannot represent every real number.

Always use ints & cast them to FP inside the loop.

Hope all goes well.
However, problem remains when i use while-loop.
And it is not easy to just use int value in loop condition.
How should i modify if i have to use the condition "x<0.8"?

Thanks a lot!
 And it is not easy to just use int value in loop condition.

 How should i modify if i have to use the condition "x<0.8"?

It is easy to use an int in the loop condition - but what is slightly trickier is how to work out how many times it will run.

If you have a start value, a step value & an end value - you can calculate how many times the loop will run as an int.

 However, problem remains when i use while-loop.

What I said in my last post applies to all types of conditional statements including all types of loops and if statements.

yep, your explanations are the same as what my professors said.
I understand now that floating point is an approximate representation of real numbers and never use floating point to make comparison.
But my program is about computational physics, ........you know,......... i use fractional number and real number very often .....╮(╯▽╰)╭
If you were testing for two floating-point numbers being equal, then rather than doing a direct comparison, subtract one from the other and test if the absolute value of the result is smaller than some limit.

 ``12345678910111213141516171819`` ``````#include #include using namespace std; int main() { double x(0), h(0.1); double diff = fabs(x - 0.8); while (diff > 1e-10) { x += h; diff = fabs(x - 0.8); cout << "diff: " << diff << endl; } cout << x << endl; }`````` ```diff: 0.7 diff: 0.6 diff: 0.5 diff: 0.4 diff: 0.3 diff: 0.2 diff: 0.1 diff: 1.11022e-016 0.8```
Last edited on
Topic archived. No new replies allowed.