簡體   English   中英

C ++中的分數表示

[英]fraction representation in c++

小數(0.9)和(0.2)在以float或double表示時會出現截斷錯誤 ,因此如果我們兩次表示0.9或0.2:

  • float變量中的第一個
  • 第二個雙精度變量
  • 這意味着其中一個大於另一個,最大的是雙變量

因此,如果我們從浮點數中減去雙精度數,則預期結果將為正

為什么打印此代碼(“正”)

float afloat = 0.9;  

if      ( 0.9 - afloat >  0 ) cout << "Positive" << endl;
else if ( 0.9 - afloat == 0 ) cout << "Equal"    << endl;
else if ( 0.9 - afloat <  0 ) cout << "Negative" << endl;

同時打印此代碼(“負數”)?

float afloat = 0.2;  

if      ( 0.2 - afloat >  0 ) cout << "Positive" << endl;
else if ( 0.2 - afloat == 0 ) cout << "Equal"    << endl;
else if ( 0.2 - afloat <  0 ) cout << "Negative" << endl;

文字0.99/10的雙精度值近似值,您的聲明

float afloat = 0.9

將此值截斷為單精度,從而丟失信息。 此代碼

float afloat = 0.9f;  

if      ( 0.9f - afloat >  0 ) cout << "Positive" << endl;
else if ( 0.9f - afloat == 0 ) cout << "Equal"    << endl;
else if ( 0.9f - afloat <  0 ) cout << "Negative" << endl;

將產生輸出

Equal

即使0.9f不完全等於分數9/10 對於不同的分數和不同的浮點格式,量化誤差的符號將有所不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM