Why would I be getting an int conversion to float wrong in c++? At a point in a program I am explicitly converting an integer with value 10 or 14 to float, and I get 0. Why would that be ? I tried static_cast, gives me same result. Since both int and float are 4 bytes, I am thinking int to float conversion is not a demotion or promotion by size ? Is it related to rounding errors etc ? Can someone please explain.
Here is the code( There is an alteration here which works fine, but I still don't know why) ---
#include <iostream>
using namespace std;
int main()
{
int n;
int sum;
cout << "Please enter the number:";
cin >> n;
int *elements = new int[n];
cout << "Please enter the elements:";
for(int i=0; i<n; i++)
{
cin >> elements[i];
}
cout << endl;
///// this approach, gives the sum right, but float(sum) fails and always gives zero.
for(int i=0, sum=0; i < n; i++)
{
sum = sum + elements[i];
}
////// This works, when sum is initialised outside of for loop. float(sum) does the right conversion as well.
//sum = 0;
//for(int i=0; i < n; i++)
//{
// sum = sum + elements[i];
//}
cout << " float n is " << float(n) << " float sum is "<< float(sum) << endl;
// float(sum) is zero, when sum is initialised from within for loop.
delete[] elements;
return 0;
}
command to compile -> g++ 3.2.cpp -o 3.2
Inputs: n = 4; elements = 1 2 3 4
It feels like something minor that I am overlooking.
Thanks for the help.