Apo*_*hay 11 c++ number-formatting
其实我正在用c ++编写范围表达式.所以我想要的是,如果我有任何表达式
x<1
Run Code Online (Sandbox Code Playgroud)
然后我的
double getMax(...);
Run Code Online (Sandbox Code Playgroud)
应该在数字行上返回一个在1.000(双精度)之前的双精度值.
我试过这样做
double getMax(double& a)
{
return (a-numeric_limits<double>::min());
}
Run Code Online (Sandbox Code Playgroud)
但我仍然得到与回报声明相同的价值.
我认为C++在cout语句中将它转换为最接近的double.
int main()
{
double a = 32;
cout<<scientific<<getMax(a)<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
3.200000e+001
Run Code Online (Sandbox Code Playgroud)
jog*_*pan 10
首先,您需要确保实际打印足够多的数字以确保double显示所有可表示的值.你可以这样做(确保你#include <iomanip>这样做):
std::cout << std::scientific << std::setprecision(std::numeric_limits<double>::max_digits10) << getMax(a) << std::endl;
Run Code Online (Sandbox Code Playgroud)
其次,numeric_limits<>::min不适合这个.如果你的起始值是1.0,你可以使用numeric_limits<double>::epsilon,这是可以表示的最小差异1.0.
但是,在您的代码示例中,起始值为32.Epsilon并不一定适用于此.在这种情况下计算正确的eps是很困难的.
但是,如果您可以使用C++ 11 (*),则cmath标题中有一个函数可以满足您的需要std::nextafter:
#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>
double getMax(double a)
{
return std::nextafter(a,std::numeric_limits<double>::lowest());
}
int main()
{
double a = 32;
std::cout << std::scientific
<< std::setprecision(std::numeric_limits<double>::max_digits10)
<< getMax(a)
<< std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我也把它放在liveworkspace上.
解释:
double nextafter(double from, double to);
Run Code Online (Sandbox Code Playgroud)
返回from的方向的下一个可表示的值.所以我std::numeric_limits<double>::lowest()在我的调用中指定了确保你得到的下一个可表示的值小于参数.
(*)见Tony D的评论如下.您可以在nextafter()没有C++ 11的情况下访问.