簡體   English   中英

C ++,與g ++相等

[英]C++, equality with g++

Why this condition is never true ? Both parts of the equation are integers, so there must be equality for index = 0, 10, 20, 30, 40. I am compiling this code using g++.

for(int index = 0; index < 50; index++){

        if ( (int) (10 * (  0.1 * index)  ==  (int)(10 * ( int ) ( 0.1 * index ) ) ) )
        {
                 std::cout << "equal";
        }
}

使用MSVS 2010編譯器不會發生這些問題...

  0  0
  1  0
  2  0
  3  0
  4  0
  5  0
  6  0
  7  0
  8  0
  9  0
  10  10
  11  10
  12  10
  13  10
  14  10
  15  10
  16  10
  17  10
  18  10
  19  10
  20  20
  21  20
  22  20
  23  20
  24  20
  25  20
  26  20
  27  20
  28  20
  29  20
  30  30
  31  30
  32  30
  33  30
  34  30
  35  30
  36  30
  37  30
  38  30
  39  30
  40  40
  41  40
  42  40
  40  40
  44  40
  45  40
  46  40
  47  40
  48  40
  49  40

您的括號是錯誤的:

if ( (int) (10 * (  0.1 * index)  ==  (int)(10 * ( int ) ( 0.1 * index ) ) ) )

應該:

if ( (int) (10 * (  0.1 * index) )  ==  (int)(10 * ( int ) ( 0.1 * index ) ) )

您正在比較兩個浮點數-0.1 * index。

您是否嘗試打印相同的單個組件? 我懷疑您會發現等式中的某處結果會有所不同。

這是因為在第二部分中,您具有(int)(0.1 * index)。 因此(int)(0.1 * 5)舍入為0。

雙方都不都是整數:

10 * (0.1 * index)

是一個雙精度數,並且使用0.1 ,您可能知道它不能以IEEE754格式精確表示(可以精確表示的唯一值是1 /(2 ^ n)的整數倍,且n> = 0)。 為了與人類通常使用的10為基數平行,計算機會或多或少地看到0.1就像您看到的0.3333333333333... (而且您沒有無限長的紙來記下所有這三個)。

您應該遵循ybungalobill的建議,順便說一句,對我來說,使用基於整數算術和模運算符的其他方法來解決您的問題要容易得多。

if (index % 10 == 0)

似乎是您要尋找的測試。

嘗試

for(int index = 0; index < 50; index++){

        if ( (int) (10 * (  0.1 * (double)index))  ==  (int)(10 * ( int ) ( 0.1 * (double)index ) ) )
        {
                 std::cout << "equal";
        }
}

暫無
暫無

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

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