【发布时间】: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++