【例422】 数学课上在一节生动有趣的数学课上老师问同学们:给出一个浮点数怎么判断这个数离前后相邻两个整数哪个更近则输出距离更近的整数。请你按照四舍五入原则编程输出这个数。【输入】输入一行包含 1 个数:n00≤n≤1000000表示题目要求输入的浮点数。题目保证输入浮点数小数点后保留最多8位。【输出】输出共计一行包含一个数表示题目所求的距离更近的整数请用c++代码写出
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double n;
cin >> n;
int intPart = static_cast<int>(n); // 获取整数部分
double decimalPart = n - intPart; // 获取小数部分
if (decimalPart >= 0.5) {
cout << intPart + 1 << endl;
} else {
cout << intPart << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/iifj 著作权归作者所有。请勿转载和采集!