在c ++中将double转换为int输1

far*_*oft 2 c++ double type-conversion

可能重复:
为什么这个double to int转换不起作用?

在c ++中将double转换为int输1

#include <iostream>
#include <cmath>
using namespace std;

void main() {

    double num = 1234.34;
    int numInt = num;
    double numAfterPoint = num - numInt; // 0.34

    int counter = 1;
    double numFloatPower = numAfterPoint;

    while (true) {
        numFloatPower = numAfterPoint * pow(10.0, counter);
        cout << numFloatPower << " > " << (int)numFloatPower << " ";
        system("pause");
        counter++;
    }

}
Run Code Online (Sandbox Code Playgroud)

目前的结果:

3.4 > 3 Press any key to continue . . .
34 > 33 Press any key to continue . . .
340 > 339 Press any key to continue . . .
3400 > 3399 Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

结果应该是:

3.4 > 3 Press any key to continue . . .
34 > 34 Press any key to continue . . .
340 > 340 Press any key to continue . . .
3400 > 3400 Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

等......

ken*_*ytm 5

cast-to-int操作(int)doubleValue执行截断,这意味着如果数字在内部表示为33.999999999 ...它将被截断为33.

使用round(),如果你需要进行取整(3.9→4,3.4→3).


注意:

  • 1234.34实际上是1234.33999999999991814547684044 ...因为它无法使用有限数量的二进制数字来精确表示,所以在第53位它将被舍入
  • 因此你的0.34实际上是0.33999999999991814547684044 ......,
  • 你的3.4实际上是3.3999999999991814547684044 ......,
  • 你的34实际上是33.999999999991814547684044 ...,
  • 你的340实际上是339.99999999991814547684044 ......,
  • 等等