2017-04-19 160 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,只是谷歌搜索:)