【问题标题】:How to format a float using sprintf where precision may vary如何在精度可能不同的情况下使用 sprintf 格式化浮点数
【发布时间】:2014-04-29 09:44:00
【问题描述】:

我必须打印一个浮点值,但是在编译时不知道精度。 所以这个参数必须作为参数传递。如何做到这一点。 在 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, 3.148257);
   std::cout << str2 << std::endl;  //Prints "Value = <null>"
   return 0;
}

【问题讨论】:

  • 您确定需要使用 sprintf 吗?使用流很容易。
  • 你试过*的宽度吗?
  • 您找到合适的解决方案了吗?如果是这样,您应该接受最有用的答案。

标签: c++


【解决方案1】:

你需要

"%.*f"

语法,其中“*”指的是下一个参数。

这都是documented

【讨论】:

    【解决方案2】:

    如果我理解你的问题,你可以使用 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;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用std::stringstream 将float 转换为std::string。 如果你想使用冲刺。而不是使用* 作为宽度。 Details here.

      【讨论】:

        【解决方案4】:

        如果您可以使用 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;
        }
        

        【讨论】:

          【解决方案5】:

          如果您想即时找到小数位数,您可以执行以下操作来计算小数位数。这意味着您根本不必传递格式字符串。

          #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;
          }
          

          【讨论】:

          • 对于大多数数字,while 将无限循环。
          • 已修复 - 尽管我必须将其限制为小数点后 10 位。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-30
          • 1970-01-01
          • 1970-01-01
          • 2016-12-06
          • 1970-01-01
          相关资源
          最近更新 更多