在 C++ 中将字符串转换为具有完整有效数字的浮点数 [已修复在 Dev C++ 中的工作]
Convert string into float in C++ with full Significant figures [Fixed working in Dev C++]
I want to convert the String which contains numerical Float into Float or Double Data type values with full significant figures Please help me to fix this
#include <sstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string q = "23.3453535";
float f;
istringstream(q) >>f;
f=1.0*f; // stack-overflow viewer it is an example because i want to process this float value
cout<<f;
}
/*OutPut is:
23.3454
but i want this
23.3453535
*/
如果您想控制精度,请包含 #include <iomanip>
并使用 std::cout << std::setprecision(17);
来设置您想要的位数。此外,float 具有 6 位有效位精度,而 double 具有 12 位精度。因此,只要您的字符串的十进制位数超过 6 位,就有可能失去精度。
这里有两个问题:
您 运行 进入 std::ostream
上浮点输出的默认格式,即 6 位数字。使用 std::setprecision(n)
提高精度以覆盖足够的小数位。
您正试图从 float
中获得比它支持的更高的精度。 "23.3453535"
的长度为 9 位,因此每个数字有 3.3 位,大约需要 30 位来存储此数字并保留所有位。 (确切地说,您需要 ceil(log(233453535)/log(2))
,即 28)。 float
只有 23 位来存储尾数,因此当值在可表示范围内时,最后的一些数字将消失。您可以使用 double
而不是 float
来解决此问题 - 但由于 float
,您将永远不会获得 9 个有效的十进制数字。
I want to convert the String which contains numerical Float into Float or Double Data type values with full significant figures Please help me to fix this
#include <sstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string q = "23.3453535";
float f;
istringstream(q) >>f;
f=1.0*f; // stack-overflow viewer it is an example because i want to process this float value
cout<<f;
}
/*OutPut is:
23.3454
but i want this
23.3453535
*/
如果您想控制精度,请包含 #include <iomanip>
并使用 std::cout << std::setprecision(17);
来设置您想要的位数。此外,float 具有 6 位有效位精度,而 double 具有 12 位精度。因此,只要您的字符串的十进制位数超过 6 位,就有可能失去精度。
这里有两个问题:
您 运行 进入
std::ostream
上浮点输出的默认格式,即 6 位数字。使用std::setprecision(n)
提高精度以覆盖足够的小数位。您正试图从
float
中获得比它支持的更高的精度。"23.3453535"
的长度为 9 位,因此每个数字有 3.3 位,大约需要 30 位来存储此数字并保留所有位。 (确切地说,您需要ceil(log(233453535)/log(2))
,即 28)。float
只有 23 位来存储尾数,因此当值在可表示范围内时,最后的一些数字将消失。您可以使用double
而不是float
来解决此问题 - 但由于float
,您将永远不会获得 9 个有效的十进制数字。