PCDVD數位科技討論區

PCDVD數位科技討論區 (https://www.pcdvd.com.tw/index.php)
-   七嘴八舌異言堂 (https://www.pcdvd.com.tw/forumdisplay.php?f=12)
-   -   請問各位這題c語言的while迴圈的答案為何是無限 (https://www.pcdvd.com.tw/showthread.php?t=594177)

si3568i 2006-02-21 03:51 AM

請問各位這題c語言的while迴圈的答案為何是無限
 
#include <stdio.h>
#include <stdlib.h>
int main(void){
int counter=0;
float total=0.00;
while(total!=1.00){
total=total+0.01;
counter=counter+1;
printf("每次的total=%f\n",total);
printf("每次的counter=%d\n",counter);
}
printf("答案是:%d",counter);
system("PAUSE");
return 0;
}
------------------------
compile之後執行的結果也的確是如此,因為到了某一數值(0.830000)時後面的數字開始亂跳,使得迴圈永遠成立,只是為何條件設定是0.01累加,為何尾數應該是0的部分會成亂數跳躍呢?謝謝各位

result12 2006-02-21 04:17 AM

while(total!=1.00)
沒詳細研究其他部分
不過我的經驗是,不要這樣用
只要 total != 1.00 ,當 total <= 0.99 或 >= 1.01
這個loop都會一直下去

doberman 2006-02-21 04:47 AM

我想是因為float在記憶體裡的儲存方式Significant digits、Exponent length、Mantissa length等,所以計算時其實都是以逼近值在作計算,

所以用 " 不等於1.00 " 作判定時會失效,

通常都是給一個精確度的限制範圍給浮點數作運算比較保險,
譬如 " if < 1.00000001 then return true " 之類的。

這是逼近1.00時的數值:

total=0.98999935
counter=99
total=0.99999934
counter=100
total=1.00999939
counter=101



這是要求輸出小數點後32位數時的情形:

total=0.00999999977648258210000000000000
counter=1
total=0.01999999955296516400000000000000
counter=2
total=0.02999999932944774600000000000000
counter=3
total=0.03999999910593032800000000000000
counter=4
total=0.05000000074505806000000000000000
counter=5
total=0.06000000238418579100000000000000
counter=6
total=0.07000000029802322400000000000000
counter=7
total=0.07999999821186065700000000000000
counter=8
total=0.08999999612569809000000000000000
counter=9
total=0.09999999403953552200000000000000
counter=10
total=0.10999999195337296000000000000000
counter=11


有錯請指正∼ :ase

si3568i 2006-02-21 04:54 AM

我想正如doberman兄所說的,應該這個緣故。沒遇過還真的不知道浮點數的累進常會出現不精確的現象。

C語言樂趣多,但是除錯要人命。><"

doberman 2006-02-21 05:05 AM

這是用" while ( total < 1.00000001 ) " 的結果:
...
counter=97
total=0.97999936342239380000000000000000
counter=98
total=0.98999935388565063000000000000000
counter=99
total=0.99999934434890747000000000000000
counter=100
total=1.00999939441680910000000000000000
counter=101
???:101Press any key to continue . . .
--------------------------------------------

還真沒想過這問題,多謝樓主提醒,賺了一次經驗∼

jaw001 2006-02-21 12:09 PM

我想說的是...使用 double 代替 float, 並用 while(total<=1.0)
結果會比較精確.

student 2006-02-21 01:22 PM

while(total!=1.00)

total 在跟 1.00 比對時最好加上處裡!!
取整數,或是取小數兩位!!


所有的時間均為GMT +8。 現在的時間是09:45 AM.

vBulletin Version 3.0.1
powered_by_vbulletin 2026。