致力于 C++ 中不同数据类型之间的转换......下面的程序打印:
>"Number is 2"
>"Number is 2.5"
>"Number is 2"
请解释为什么最后一个打印输出不是“数字为 2.5”,这是我希望在 C++ 样式转换为浮动之后所期望的?
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
int iNumber = 5;
float fNumber;
// No casting - C++ implicitly converts the result into an int and saves into a float
// which is a conversion from 'int' to 'float' with possible loss of data
fNumber = iNumber / 2;
cout << "Number is " << fNumber << endl;
// C-style casting not recommended as not type safe
fNumber = (float) iNumber / 2;
cout << "Number is " << fNumber << endl;
// C++ style casting using datatype constructors to make the casting safe
fNumber = static_cast<float>(iNumber / 2);
cout << "Number is " << fNumber << endl;
_getch();
return 0;
}