Beginner here.
Why is this an endless loop ?
for (p = 0; p < 5; p += 0.5)
{
printf("p=%2.2f\n",p);
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You see an endless loop because your p is of an integral type (e.g. an
int). No matter how many times you add0.5to an int, it would remain 0, becauseinttruncates double/fp values assigned to it. In other words, it is equivalent to a loop where you add zero on each step.If you make
pafloator adouble, your problem would go away.EDIT (Suggested by Oli Charlesworth’s comment)
It is worth noting that using floats and doubles to control loops is discouraged, because the results are not always as clean as in your example. Changing the step from
0.5(which is 2 to the negative power of 1) to0.1(which is not an integral negative power of 2) would change the results that you see in a rather unexpected way.If you need to iterate by a non-integer step, you should consider using this simple pattern: