我正在使用 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;
}
最佳答案
由于 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/