c++ - 寻找中位数的 Ceil 函数

标签 c++

我正在使用 Bjarne Stroustroup 的《C++ 编程原理和实践》学习 C++。在下面的寻找中位数的问题中,我对 ceil 函数有问题。比如说,我输入 14 个条目,那么 a 的值应该是 6,b 的值应该是 7。但是 b 的值应该是 7。即将推出 6。

#include "std_lib_facilities.h"

using namespace std;

int main() 
{ vector<double> temps;
  for(double temp;cin>>temp;)
     {temps.push_back(temp);
     }
  sort(temps);
  for(double temp : temps)
     cout << temp << " " ;
  int size = temps.size();

  if(size%2 == 0)
    { int a,b,c;
      a = temps[floor((size + 1)/2) - 1]; cout << a;
      **b = temps[ceil((size + 1)/2) - 1 ]; cout << b;**
      cout<<"Median temperature:"<<(a+b)/2<<'\n';
    }
  else
    cout<<"Median temperature:"<<temps[((size + 1)/2) - 1]<<'\n';
return 0;
}

std_lib_facilties.h link

最佳答案

由于 size 是一个 int(size+1)/2 将执行整数除法,并且仅返回整个部分该部门的。如您所见,对它应用 ceil 是没有意义的。

您可以通过将 size 定义为 double 或将其内联转换来解决此问题:

**b = temps[ceil((((double)size) + 1)/2) - 1 ];

关于c++ - 寻找中位数的 Ceil 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536729/

相关文章:

c++ - 检查输入字符串在 C++ 中是否有前导或尾随空格?

c++ - 如何在运行时使用 C++ "compile"表达式?

C++ 模板将某种类型的成员添加到类中

c++ - 从 BHO ( C++ ) 向 CAxWindow 上的 JS 公开方法

c++ - Container end() 迭代器如何在(例如)Container 大小变化时演变

c++ - 从 C++ 中的 std::function 访问模板化 lambda

c++ - 如何让 C++ 编译器间接推导 T?

c++ - 我应该删除 QDebug header 以进行发布吗?

c++ - 如何根据优先级和关联性解析(复杂的)声明?

iphone - c++ 类方法上的performSelector?