Reputation: 11
I need to round off each decimal values to its nearest whole number, anything less than 0.4 to be rounded off to 0, and 0.5 and above to be rounded off to 1. But when i try that in C++ no matter which function i try to use it seems to round of 0.5 to 0 and not 1, it works fine for other decimal values but for 0.5, this happened to both positive and negative values as well.
Here is the code that i just made:
#include <iostream>
#include <vector>
#include <cmath>
int main(){
using namespace std;
int a, b, n;
cin >> n;
int arr[n];
double prod;
for(int i = 0; i < n; i++){
cin >> a >> b;
prod = a/b;
if(prod < 0){
arr[i] = (int)(prod-0.5);
} else {
arr[i] = (int)(prod+0.5);
}
}
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}
}
Here is the sample dataset that i have used for my testing (tried it with others as well but this was the one that was still there on my laptop so im putting it here):
`13 --> Size of the array.
571518625 -24104
-1893729058 -436796
2104753595 -158270
-822607240 72830
0 -79061
-627632490 -31441
369212137 18046
976324350 -57100
487246561 24578
-1317758661 119682
0 5341
1098940248 -68272
-923153725 61895`
The answer I got:
-23710 4335 -13298 -11294 0 19962 20459 -17098 19824 -11010 0 -16096 -14914
Against the answer I was suppose to get:
-23711 4336 -13299 -11295 0 19962 20460 -17099 19825 -11011 0 -16097 -14915
Upvotes: 1
Views: 102