这个字符串要打印多少次?

时间:2020-12-01 23:54:19

I saw this code on Exam: the question is how many times this string will be printed.

我在考试中看到了这段代码:问题是这个字符串将被打印多少次。

I thought first it will be 10 times but this is wrong. Can someone tell me why my answer is wrong. This is part of a code in the C language.

我原以为会是10倍,但这是错的。有人能告诉我为什么我的答案是错的吗?这是C语言代码的一部分。

for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) {
    printf("lbc");
}

2 个解决方案

#1


7  

Assuming x is a 32 bit floating point:

假设x是一个32位浮点数:

Floating point values have a limited resolution. 100000001 is 1*10^8 so you lose your 1 at the end. If you would add 1, it again gets lost because the next float value is 1.00000008*10^8. You can add as many 1s as you like the result will always be the same.

浮点值的分辨率有限。100000001是1 * 10 ^ 8所以你失去1。如果你想加1,再丢失,因为接下来的浮动值是1.00000008 * 10 ^ 8。你可以添加任意数量的1,结果总是一样的。

That is the reason why your code is an endless loop.

这就是为什么您的代码是一个无止境的循环。

#2


5  

float x = 100000001.0f;

will initialize x with the nearest representable float, which is 100000000. Adding 1 to this value will lead to the same value.

将用最接近的可表示浮点数初始化x,即100000000。将1添加到这个值将导致相同的值。

If you print the value of x in the loop you will see what happen: http://ideone.com/3FJGTz

如果在循环中打印x的值,您将看到发生了什么:http://ideone.com/3FJGTz

#1


7  

Assuming x is a 32 bit floating point:

假设x是一个32位浮点数:

Floating point values have a limited resolution. 100000001 is 1*10^8 so you lose your 1 at the end. If you would add 1, it again gets lost because the next float value is 1.00000008*10^8. You can add as many 1s as you like the result will always be the same.

浮点值的分辨率有限。100000001是1 * 10 ^ 8所以你失去1。如果你想加1,再丢失,因为接下来的浮动值是1.00000008 * 10 ^ 8。你可以添加任意数量的1,结果总是一样的。

That is the reason why your code is an endless loop.

这就是为什么您的代码是一个无止境的循环。

#2


5  

float x = 100000001.0f;

will initialize x with the nearest representable float, which is 100000000. Adding 1 to this value will lead to the same value.

将用最接近的可表示浮点数初始化x,即100000000。将1添加到这个值将导致相同的值。

If you print the value of x in the loop you will see what happen: http://ideone.com/3FJGTz

如果在循环中打印x的值,您将看到发生了什么:http://ideone.com/3FJGTz