版权声明:[email protected] https://blog.csdn.net/lytwy123/article/details/84566149
1.题目描述:
2.算法分析:
首先肯定是定义一个double类型数组存放数据,然后的一个问题是怎么判断浮点数最近的整数的差,
使用round函数即可
floor : 不大于自变量的最大整数
ceil :不小于自变量的最大整数
round:四舍五入到最邻近的整数
floor(),ceil() 需包含头文件math函数库
具体可以查C++帮助文档
然后我们使用C++的sort函数进行排序,写一个自定义排序方法cmp
当发现
两个浮点数相同则按照原来的大小排列
而不相等则按照谁离整数最近谁在前
3.源代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const double EPSILON = 1e-6;
double num[105];
bool cmp(double x,double y){
double dx = fabs(x - round(x));
double dy = fabs(x - round(y));
if(fabs(dx - dy) < EPSILON){
return x < y;
}
return dx < dy;
}
int main(){
int N;
scanf("%d", &N);
for (int i = 0 ; i < N ; i++){
scanf("%lf", &num[i]);
}
sort(num , num + N , cmp);
for (int i = 0 ; i < N ; i++){
if(i != N - 1){
printf("%.6lf ", num[i]);
}else{
printf("%.6lf\n", num[i]);
}
}
return 0;
}
可以关注一下Blog:http://47.107.118.184