![]() |
||
|
Master Member
![]() ![]() ![]() ![]() 加入日期: Feb 2002 您的住址: 楓葉與霜晶的華爾滋
文章: 1,862
|
請問各位這題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的部分會成亂數跳躍呢?謝謝各位
__________________
|
|||||||
|
|
|
Advance Member
![]() ![]() 加入日期: Mar 2003 您的住址: Land of living sky
文章: 334
|
while(total!=1.00)
沒詳細研究其他部分 不過我的經驗是,不要這樣用 只要 total != 1.00 ,當 total <= 0.99 或 >= 1.01 這個loop都會一直下去 |
||
|
|
|
*停權中*
加入日期: Mar 2004
文章: 477
|
我想是因為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 有錯請指正∼ ![]() |
|
|
|
Master Member
![]() ![]() ![]() ![]() 加入日期: Feb 2002 您的住址: 楓葉與霜晶的華爾滋
文章: 1,862
|
我想正如doberman兄所說的,應該這個緣故。沒遇過還真的不知道浮點數的累進常會出現不精確的現象。
C語言樂趣多,但是除錯要人命。><"
__________________
|
|
|
|
*停權中*
加入日期: Mar 2004
文章: 477
|
這是用" 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 . . . -------------------------------------------- 還真沒想過這問題,多謝樓主提醒,賺了一次經驗∼ |
|
|
|
New Member
加入日期: Jul 2004
文章: 5
|
我想說的是...使用 double 代替 float, 並用 while(total<=1.0)
結果會比較精確. |
|
|
|
Amateur Member
![]() 加入日期: Jul 2005
文章: 36
|
while(total!=1.00)
total 在跟 1.00 比對時最好加上處裡!! 取整數,或是取小數兩位!! |
|
|