Reputation: 439
I'm writing a C++ code that divides two floats and outputs a whole number. but when I try dividing and rounding off using the round() function the number I get:
8878323 / 5 = 1.77566e+06
Every other number is being outputted as a whole number. Not sure why this one isn't.
code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a[30] = {41, 2733017,17473, 3164246, 105, 8015, 150, 12, 1090473, 81, 135, 15539, 8251, 7029, 9589930, 6027963, 5959834, 12661, -884988, 7258221, 8878323, 92, 1200422, 16645, -3062617, 147, 5421, 22, 9495996, 2302743};
float b[30] = {2, 367, 506, 763, 14, 972, 12, 8, 889, 6, 10, 1840, 1294, 1834, 3822029, -1641686, 126, 1826, -2463550, 509, 5, 8, 717, 1270, 3789065, 14, 806, 4, 307, 803};
float ans[30];
for(int i=0; i<30; i++) {
ans[i] = a[i]/b[i];
ans[i] = round(ans[i]);
}
for(int i=0; i<30; i++)
cout << ans[i] << " ";
return 0;
}
Upvotes: 1
Views: 363
Reputation: 104524
It's just a precision issue with cout. Pretty much any sufficiently large float will generate this issue.
Try this:
Add #include <iomanip>
to the top of your program.
Then adjust your cout statement to use a setprecision specifier:
cout << setprecision(15) << ans[i] << " ";
Alternatively, you could simply cast the result to a long before printing it
cout << (long)(ans[i]) << " ";
Upvotes: 2