2009-04-27 88 views
0

最有可能的一個非常簡單的問題,請保留任何的答案很容易理解我仍然很新的這一點:小數和C++中的Pow功能

我正在做一個小應用程序,我需要使用權力進行一些計算。經過一番研究,我發現了cmath的pow函數,並且已經發揮了作用。最後,我想出了這個剪切,它的工作原理:

#include <iostream> 
#include <cmath> 
using namespace std; 

int main() 
{ 
    float dummy2, test(6.65); 
    dummy2 = (float) pow((float) 3.57, test); 
    cout << dummy2; 

    return 0; 
} 

它返回正確的答案(4734.17),但只有兩位小數。我想要5位小數。

我在這裏做錯了什麼?我使用錯誤的數據類型(浮動)?或者它是否僅限於使用2dp的pow函數?

我可以,如果它來定義常量與我想要的值,因爲它只會是4或5總和,我需要這個精度,但如果有可能讓程序計算出它會很棒。

謝謝

+0

谷歌是你的朋友。 [這些結果](http://www.google.com/search?q=cout+decimal+places)和[這些結果](http://www.google.com/search?q=cout+float+精度)有你想要的,即你需要使用setprecision()作爲cout參數。 – 2009-04-27 23:00:18

回答

3

爲了更好的精度,你應該使用雙精度。雙打對漂浮物有15個數字的精度爲7。

+0

15和7位十進制數字只是粗略值。特別是,對於浮動7可能有點樂觀...... – dmckee 2009-04-28 01:13:21

6

我會像fbinder說的那樣做,並且使用雙精度來提高精度。 爲了解決你的問題,你有兩種選擇,C風格和C++風格。

C-風格

#include <cstdio> 
printf("%.5f", dummy2); 

C++風格

#include <iomanip> 
std::cout << setprecision(5) << dummy2 << std::endl; 

OR

std::cout.precision(5); 
std::cout << dummy2 << std::endl; 
// continue to use cout to output 5 decimal places