2017-04-19 108 views
-5
#include<stdio.h> 
void main() 
{ 
    int i; 
    float x=0.8; 
    for(i=0; i<100; i++) 
    x=x*(1-x)*5; 
    printf("%f \n",x); 
} 

据我所知,它看起来很简单,回答0.80000000但真正的答案是别的。它的运行时间错误与输出值“-inf”。为什么?这个程序的输出是什么?

+4

为什么你认为它应该是'0.8'? –

+0

我会说它会收敛到无穷大,因为你正在执行100次正方形。并不令人惊讶。 –

+1

我建议你把'printf'放到循环中,然后你会在第23次迭代中看到值“escape”。这种调查方法将在未来的道路上得到无限回报。 –

回答

3

它表示负无穷。

EEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately. You can also deliberately set a floating-point variable to any of them, which is sometimes useful. Some examples of calculations that produce infinity or NaN:

这是你的输出是代码

0.800000 
0.800000 
0.800000 
0.800001 
0.799996 
0.800011 
0.799966 
0.800103 
0.799692 
0.800923 
0.797227 
0.808280 
0.774816 
0.872380 
0.556664 
1.233946 
-1.443383 
-17.633698 
-1642.905029 
-13503899.000000 
-911776526893056.000000 
-4156682286578109086379962007552.000000 
-inf 
after this -inf -inf 

,因为该值超出平

+0

okey。我现在不去看价值。如果我仅迭代这个代码5次,它仍然显示运行时错误。为什么? [链接](https://ideone.com/shXVur) –

+0

@vishal_ag代码工作正常,输出正常,这是在线IDE所给出的错误,因此忽略。尝试在系统中运行代码。 –

2

浮点误差范围:尽量采取循环从0到24,看到了输出, 你得到0.800018左右,这改变了1-x部分成为否定答案(大约40sh循环),所以在第100个这是一个非常低的负数,它基本上是-inf。

它基本上是因为x = 0.8;不是0.8尖锐的,而是非常接近0.8的数字,随着循环次数的增加,直到它影响计算。

有很多的解决方法 - 一种方法是每次轮次x,只是谷歌搜索:)