当前位置: 代码迷 >> 综合 >> 浮点数比较与排序
  详细解决方案

浮点数比较与排序

热度:83   发布时间:2024-02-28 14:50:40.0

概要:使用std::sort()排序,注意浮点数不能比较;

浮点数比较

bool float_equal(float &f1,float &f2)

{

  return (f1>f2-1e-6)&&(f1<f2+1e-6);

}

bool float_greater(float &f1,float &f2)

{

  return (f1>f2-1e-6);

}

bool float_less(float &f1,float &f2)

{

  return (f1<f2+1e-6);

}

}

浮点数排序

#include <algrothorm> // for greater<int>()

float f_v[5] = { 1.0,2.0,3,0,2.1,1.1}

std::sort(f_v,f_v+5)//默认升序排列===默认比较函数

 

std::vector<float>  f_v1;

std::vector<float>::iterator f_it;

for(int k=0;k< 5;k++)

{

 f_v1.push_back(f_v[k]);

}

std::vector<float>  f_v2(f_v1);

std::sort(f_v1.begin(),f_v1.end(),greater<float>());//降序排列,最大的排在首位

std::sort(f_v1.begin(),f_v1.end(),float_greater);//降序排列,最大的排在首位,===自定义比较函数

 

 

 

  相关解决方案