我需要将每个小数值四舍五入为最接近的整数,任何小于 0.4 的值都四舍五入为 0,0.5 及以上的值四舍五入为 1。 但是当我在 C++ 中尝试时,无论我尝试使用哪个函数,它似乎都会将 0.5 舍入到 0 而不是 1,对于其他十进制值它工作得很好,但对于 0.5,这也发生在正值和负值上。
这是我刚刚制作的代码:
#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] << " ";
}
}
这是我用于测试的示例数据集(也与其他人一起尝试过,但这是我的笔记本电脑上仍然存在的数据集,所以我把它放在这里):
`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`
我得到的答案:
-23710 4335 -13298 -11294 0 19962 20459 -17098 19824 -11010 0 -16096 -14914
与我应该得到的答案相反:
-23711 4336 -13299 -11295 0 19962 20460 -17099 19825 -11011 0 -16097 -14915
#include <iostream>
#include <vector>
#include <cmath>
int main() {
using namespace std;
const int a[]{ -1, 0, +1 }, b[]{ 2, 2, 2 }, n = 3;
//cin >> n;
double arr[n];
double prod;
for (int i = 0; i < n; i++) {
//cin >> a >> b;
prod = static_cast<double>(a[i]) / b[i]; // <--
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] << " ";
}
}