Code:
#define N 4
float unknowns[N] = {71/129, 539/1461, 1493/8507, 17/33};
for(int i = 0; i < N; i )
{
cout << unknowns[i] << " ";
}
cout << endl << endl;
Output:
0 0 0 0
For some reason the program is outputing the numbers in the array as integers and not as floats and I don't know why. How can I fix this?
This code for example works, and I tried casting them in the array itself but it still didn't work:
cout << (float)71/129 << " " << (float)539/1461 << " " << (float)1493/8507 << " " << (float)17/33 << endl;
Output:
0.550388 0.368925 0.175503 0.515152
CodePudding user response:
The numbers you shown are implicitely casted to integers, thus the result is always zeros, and thats what you get by the zero results. When you tell the compiler those are floats (e. g. by adding a zero) the result is also a float. Heres a working code example:
int main() {
int N = 4;
float unknowns[N] = {71.0/129.0, 539.0/1461.0, 1493.0/8507.0, 17.0/33.0};
for(int i = 0; i < N; i )
{
std::cout << unknowns[i] << " ";
}
std::cout << std::endl << std::endl;
return 0;
}
CodePudding user response:
The problem is, you are doing integer division (e.g., 71/129) and storing the value later in float. The result of integer is division of all your values is 0.
Use float division while constructing the array (use 71.0/129.0).
The code is:
define N 4
float unknowns[N] = {71.0/129.0, 539.0/1461.0, 1493.0/8507.0, 17.0/33.0};
for(int i = 0; i < N; i )
{
cout << unknowns[i] << " ";
}
cout << endl << endl
