C++ 在精度可能不同的情况下,如何使用sprintf格式化浮点

C++ 在精度可能不同的情况下,如何使用sprintf格式化浮点,c++,C++,我必须打印一个浮点值,但是编译时不知道精度。 所以这个参数必须作为agment传递。如何做到这一点。 在windows中,使用CString,format函数有助于实现这一点。 如何在没有CString的情况下实现这一点。 代码: intmain() { /*下面的代码段工作正常*/ char-str[80]; sprintf(str,“Pi值=%.3f”,3.147758); std::cout您可以使用它将float转换为std::string。 如果您想使用sprint.than,请对宽度

我必须打印一个浮点值,但是编译时不知道精度。 所以这个参数必须作为agment传递。如何做到这一点。 在windows中,使用CString,format函数有助于实现这一点。 如何在没有CString的情况下实现这一点。 代码:

intmain()
{
/*下面的代码段工作正常*/
char-str[80];
sprintf(str,“Pi值=%.3f”,3.147758);
std::cout您可以使用它将float转换为std::string。
如果您想使用sprint.than,请对宽度使用
*

您需要

"%.*f"
语法,其中“*”表示下一个参数


仅此而已。

如果我正确理解您的问题,您可以使用setPrecision(..)来实现所需的结果:

#include <iostream>
#include <iomanip> // for setprecision()
int main()
{
    using namespace std;

    cout << setprecision(16); // show 16 digits
    float fValue = 3.33333333333333333333333333333333333333f;
    cout << fValue << endl;
    double dValue = 3.3333333333333333333333333333333333333;
    cout << dValue << endl;
}
#包括
#包含//用于setprecision()
int main()
{
使用名称空间std;

cout如果可以使用iomanip,请执行以下操作:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int numOfDecimals = 2;// this controls precision. change to what ever you want
    float PI = 3.147758;

    cout << fixed << setprecision(numOfDecimals);
    cout << PI << endl;
    return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
int numodecimals=2;//此选项控制精度。可随时更改为所需的值
浮点数PI=3.147758;

cout如果您想快速查找小数位数,您可以执行如下操作来计算小数位数。这意味着您根本不必传入格式字符串

#include <iostream>
using namespace std;

int main() 
{
double dNum = 3.14159265359, threshold = 0.00000000005;
double temp = dNum;
int count = 0;
while((temp - (int)temp) > threshold) 
{
    temp *= 10;  
    threshold *=10;
    count++;              
} 
char buffer[50];
sprintf(buffer,"value is = %.*f",count,dNum);
return 0;
}
#包括
使用名称空间std;
int main()
{
双dNum=3.14159265359,阈值=0.00000000005;
双温=dNum;
整数计数=0;
而((温度-(内部温度)>阈值)
{
温度*=10;
阈值*=10;
计数++;
} 
字符缓冲区[50];
sprintf(缓冲区,“值为%.*f”,计数,dNum);
返回0;
}

你确定需要使用sprintf吗?这对streams来说很简单。你有没有尝试过宽度方面的
*
?你找到合适的解决方案了吗?如果有,你应该接受最有用的答案。对于大多数数字,while将无限循环。已修复-尽管我不得不将其限制在小数点后10位。
#include <iostream>
using namespace std;

int main() 
{
double dNum = 3.14159265359, threshold = 0.00000000005;
double temp = dNum;
int count = 0;
while((temp - (int)temp) > threshold) 
{
    temp *= 10;  
    threshold *=10;
    count++;              
} 
char buffer[50];
sprintf(buffer,"value is = %.*f",count,dNum);
return 0;
}