Working on casting between different datatypes in C++... The program here below prints:
>"Number is 2"
>"Number is 2.5"
>"Number is 2"
Please, explain why the last printout is not "Number is 2.5" which I would expect after the C++ style cast to float?
#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;
}