2012-10-02 29 views
15

的一員,我嘗試編譯這段代碼:「圓」是不是「性病」

#include <cmath> 
double gravity (double level) { 
    return 0.02 * std::round(level); 
} 

但GCC告訴我:

error: 'round' is not a member of 'std' 

我知道我已經使用了round功能多次在ISO C++ 98之前。通常,round::round都可以工作。

什麼給?我正在編制g++ -std=c++98 -Wall -pedantic。 切換到std=c++0x的作品。

但是,爲什麼不合格/匿名round::round都工作,如果std::round沒有?

+1

不,它不是:http://www.cplusplus.com/reference/clibrary/cmath/ –

+3

http://stackoverflow.com/questions/485525/round-for-float-in-c – Derek

+2

@HugoCorráyes它是,但只在C++ 11中:http://en.cppreference.com/w/cpp/numeric/math/round – juanchopanza

回答

3

在C++ 03標準,對於標準C庫規範參考是ISO/IEC 9899:1990(C90),其包括round功能。在C++ 11中,它是ISO/IEC 9899:1999(C99),其中確實包含了round函數

在每個C++標準<cmath>的內容是相同math.h從相應的標準C庫除了少數改變(§26.8/ 4在C++ 11):

的這些內容標題[<cmath><cstdlib>]是一樣的標準C庫頭分別<math.h><stdlib.h> [...]

他們,但是,在std命名空間範圍(§17.6在C++ 11中):

但是,在C++標準庫中,聲明(C中定義爲宏的名稱除外)在名稱空間範圍(3.3.6)內命名空間標準。

所以,把它包起來,在round功能在C++ 03可用,所以與-std=c++0x選項編譯,並把它稱爲std::round

+0

謝謝,但如果cmath和math.h相同,它不能解釋爲什麼:: round作品,但std :: round不能。我用g ++編譯-std = C++ 98 -Wall -Wextra -pedantic。 – QuasarDonkey

+0

我給了它一個測試,你是對的。我只能想象''不會'#include '並且只把C90版本的函數拉到'std'中,所有其他東西都在全局名稱空間中。在'std'中應該可以使用的函數,比如'sin',確實可以像'std :: sin(90.0)'一樣工作。 –

11

我已經做了一些研究,這裏是我發現:

roundISO C++ 11定義,因爲它包含了ISO C99標準庫。

round不是ISO C++ 98,它使用ISO C90標準庫的一部分。

這就是爲什麼它不在命名空間stdC++ 98

但是g++是(錯誤地)包括C99標頭,即使與-std=c++98 -pedantic編譯,這應該禁用所有非標準東西:

GNU_SOURCE由G定義++和...它意味着_USE_ISOC99

(從http://gcc.gnu.org/ml/gcc/2002-09/msg00580.html

這就是爲什麼::round作品。

這顯然是在GCC的錯誤:Why does GCC allow use of round() in C++ even with the ansi and pedantic flags?

其他C++編譯器可能無法提供round功能(因爲它不是標準所要求的),所以我應該定義自己的。

+1

你不應該嘗試和定義你自己的回合,看看[我的回答在這裏](http://stackoverflow.com/a/24348037/1708801)它實際上比看起來更難。可悲的是類似的線程噸答案正是這樣做,他們大多數錯誤是微妙的方式。一些人得到低估,但許多人甚至接受了答案。 –

+1

這很搞笑。我在C++ 03中缺少'std :: round'的解決方法是使用''中的'round'來代替,並且依賴於一個GCC錯誤,該錯誤提供了function_。不知怎的,這個錯誤甚至不會被''繼承。幹得好,C++! –

+0

@PreferenceBean我已經遷移到C++ 11:'gcc -std = C++ 11'。它有一個'std :: round'函數,等等。 – QuasarDonkey

4

老話題,但也許有用的那些在谷歌搜索:

//TODO: C++11 got round() function defined in math.h 
float distance = sqrt((float)(plus_x * plus_x + plus_y * plus_y)); 
if (distance >= floor(distance)+0.5) distance = ceil(distance); 
else distance = floor(distance); 
3

float myRoundFunc(float toRound) 
{ 
    return std::ceil(toRound - 0.5); 
} 

這樣也就沒怎麼比較,它會正常輪。