小编evi*_*uff的帖子

如何使用 sprintf 格式化浮点数,其中精度可能会有所不同

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

int main()
{

   /* This below code segment works fine.*/
   char str[80];
   sprintf(str, "Value of Pi = %.3f", 3.147758);
   std::cout << str << std::endl; //Prints "Value of Pi = 3.148"

   /* When the precision may vary, henc It needs to be printed required on that.*/
   char str2[80];
   std::string temp = "%.3f";   //This is required as the precision may change. 
                                    // i.e I may have 4 instead 3 decimal points.
   sprintf(str2, "Value = %s", temp, …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
8874
查看次数

标签 统计

c++ ×1