far*_*oft 2 c++ double type-conversion
在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)
等......
cast-to-int操作(int)doubleValue执行截断,这意味着如果数字在内部表示为33.999999999 ...它将被截断为33.
使用round(),如果你需要进行取整(3.9→4,3.4→3).
注意: