[英]Reading float value from string upto 6 precision
我必須從字符串中讀取float值,精度最高為6,當前代碼僅讀取前6位數字。 提前致謝
template <class T>
bool from_string(T& t, const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("1456.909"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
我可以肯定它正在讀取所有數字。 問題似乎出在您的期望中。 讓我們說得更強一點:如果您以float
讀取1456.90900000000000000000000000000
會發生什么?
如果您想使用6位以上的數字,則需要使用雙精度而非浮點型。 您的問題說的是“ 6位精度”和“前6位數字”,但是您要輸入的是7位數字。
浮點數只能容納6位精度的iexyzpqrs或xy.zpqrs或xyzpq.rs。 如果要保留小數點后6 位,則需要使用double。
例如,您可以使用cout.precision(7)使其輸出更多的小數位,在這種情況下,即使C實際上並不存儲7位數字,它也會打印正確的答案,只是近似正確的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.