Visual Studio 2012和Visual Studio 2015的双重结果有所不同

时间:2018-09-20 10:46:45

标签: c++ visual-studio visual-studio-2012 visual-studio-2015

我正在Windows 7(64位)上运行数学应用程序。我们最近通过Visual Studio 2015迁移到了c ++ 11 我有一个问题,已经简化为以下小程序

#include "stdafx.h"
#include "iostream"

using namespace std;


int main()
{
    const double OM = 1.10250000000000000E-36;
    std::cout.precision(20);
    std::cout <<   OM;

    int y;
    std::cin >> y;
    return 0;
}

当我编译并运行程序时 1)在Visual Studio 2012上,我得到的结果为 1.1025000000000001e-036 2)在Visual Studio 2015和c ++ 11上,我得到的结果为 1.1025000000000000611e-36

请注意Visual Studio 2012中的额外0。我们需要具有相同的结果。 (请注意,结果不仅是一个额外的0,而且最后一个显示的数字也不同)

如何使它们相同(即我需要旧的结果并加上0)?这给我造成了很多问题,我希望得到同样的结果。

enter image description here

需要相同结果的原因。以上程序只是对差异的一个小解释。这种差异导致我的回归失败。有时,这种差异加起来会得出不同的结果。

我希望Visual Studio有一些编译器开关等,可以给我旧的结果。

1 个答案:

答案 0 :(得分:2)

具有三位数指数的Visual C ++的旧方法似乎是_set_output_format弃用的Visual C ++扩展。该文档说:

  

重要

     

该功能已过时。从Visual Studio 2015开始,它在CRT中不可用。

所以基本上,您很幸运,但并非没有希望。

您可以定义自己的双重打印功能,并将其通过std::ios_base::imbue链接到std::basic_ostream。这意味着您只需要定义一个新的locale即可。

这是解决方案的草图。您必须填写详细信息,以便代码可以与所有iostream格式设置一起正常使用,并且不能忽略诸如setprecision()之类的内容。下面的示例代码只是一个示例,它并不能完成所有这些事情。要获得完整的解决方案,您需要花点时间(但不要太多):

template <class Char>
class my_double : public std::num_put<Char>
{
public:
    static my_double * get()
    {

        static my_double * singleton = new my_double;
        return singleton;
    }
private:
    using base = std::num_put<Char>;
    //
    // This method will format your double according to your needs.
    // Refine the code so that it reads and uses all the flags from `str`
    // and uses the `fill` character.
    //
    iter_type do_put(iter_type out, std::ios_base& str, Char fill, double v) const override
    {
        if (v < 0)
        {
            v *= -1;
            *out = '-';
            ++out;
        }
        if (v == 0.0 || std::isnan(v))
        {
            return base::do_put(out, str, fill, v);
        }
        auto exponent = static_cast<int>(std::floor(std::log10(v)));
        auto significand = v / std::pow(10.0, exponent);
        // TODO: Format according to the flags in `str`
        out = base::do_put(out, str, fill, significand);
        *(out++) = 'e';
        if (exponent < 0)
        {
            *(out++) = '-';
            exponent *= -1;
        }
        *(out++) = '0' + ( (exponent / 100) % 10);
        *(out++) = '0' + ((exponent / 10) % 10);
        *(out++) = '0' + (exponent % 10);
        return out;
    }
};

int main()
{

    // !!!
    // This is how you register your formatting function for `double`
    // !!!
    std::cout.imbue(std::locale(cout.getloc(), my_double<char>::get()));
    /// your code goes here:
}