为什么round()被mingw知道,而不被visual studio编译器知道

Why round() is known by mingw but not by visual studio compiler

本文关键字:studio visual 编译器 round mingw 知道 为什么      更新时间:2023-10-16

有效的示例代码,由gcc编译,而不是由VS编译器编译:

#include <cmath>
int main()
{
    float x = 1233.23;
    x = round (x * 10) / 10;
    return 0;
}

但由于某种原因,当我在Visual Studio中编译这个时,我得到一个错误:

C3861: 'round': identifier not found

我甚至包括cmath,有人建议在这里:http://www.daniweb.com/software-development/cpp/threads/270269/boss_loken.cpp147-error-c3861-round-identifier-not-found

这个函数只在gcc中存在吗?

首先,cmath不能保证将round带入全局名称空间,因此您的代码可能会失败,即使使用最新的、符合标准的C或c++实现。请使用std::round(或#include <math.h>)

注意你的c++编译器必须支持std::round (<cmath>)的C++11。C编译器应该为round(从<math.h>)支持C99。如果您的MSVC版本在我建议的修复之后不能工作,则可能只是该特定版本是c++ 11之前的版本,或者只是不符合标准。

您也可以使用boost库:

#include <boost/math/special_functions/round.hpp>
const double a = boost::math::round(3.45); // = 3.0
const int b = boost::math::iround(3.45); // = 3

Visual Studio 2010 (C99)不支持round但ceiling和floor函数,因此您可能需要添加自己的函数,如;

long long int round(float a)
{
    long long int result;
    if (a-floor(a)>=0.5) 
       result = floor(a)+1;
    else
       result = floor(a);
    return result;
};

根据我的经验,在VS 2010中支持std::round#include <math.h>

我将使用两次floor来获得正确的四舍五入值,

long long int round(float a)
{
    long long int result = (long long int)floor(a);
    return result + (long long int)floor((a-result)*2)
};