2013-10-18 96 views
5

我無法將字符串轉換爲雙精度。我得到一個字符串,其格式爲:33.9425/N 118.4081/W將字符串轉換爲雙精度 - 丟失精度

我第一次調用我的函數trimLastChar(std::string& input)兩次,它將刪除North,South,East,West字符,然後是正斜槓。此功能正確地返回33.9425118.4081作爲std::string

我正在使用以下代碼將std::string轉換爲double ...但是問題是,轉換損失的精度 - 我懷疑它變圓了嗎?

// Location In String is what trimLastChar returns 
std::stringstream stream(locationInString); 
std::cout << "DEBUG: before: " << locationInString << " "; 
// output is a double* output = new double passed by reference to my function 
stream >> output; 
std::cout << output << std::endl; 

在這種情況下,輸出會產生:

33.9425 
118.408 

你可能注意到了,正確的值應該是118.4081但1缺少...

任何想法如何解決?或者更重要的是,爲什麼發生這種情況?

+2

...你應該檢查你的輸出格式,我猜這只是cout上格式化的問題。 – IdeaHat

回答

7

輸入時精度不會丟失。它正在輸出中丟失。

#include <iostream> 
using std::cout; 
using std::endl; 
int main() 
{ 
    double v = 118.4081; 
    cout << v << endl; 
    cout.precision(10); 
    cout << v << endl; 
} 

輸出:

$ g++ -Wall x.cpp && ./a.out 
118.408 
118.4081 
$ 
+0

謝謝......那就是訣竅! – Adam

3

您可能有比輸出顯示更多的數字。默認情況下,只顯示少量的數字,您需要使用std::setprecision來查看更多數字。嘗試

std::cout << std::setprecision(10) << output << std::endl;