最大双宽度的Printf格式说明符
printf format specifier for max double width
我有以下数组:
float a[]={ 1.123 12.123, 123.123, 12345.123};
如何创建以下输出(裁剪小数部分):
1.123
12.12
123.1
12345
float a[]={ 1.123, 12.123, 123.123, 12345.123};
for(int i = 0 ; i < 4 ; i++) {
int digits = 4 - log10(a[i]);
digits = digits < 0 ? 0 : digits;
digits = digits > 3 ? 3 : digits;
printf("%.*fn",digits,a[i]);
}
int main()
{
float a[]={ 1.123, 12.123, 123.123, 12345.123};
for(int i=0; i<4; i++)
{
std::stringstream ss;
ss << a[i];
std::string s;
ss >> s;
s.resize(5); // it only works with 99999
cout << s << "n";
}
cout << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
int main(int argc,char* argv[]){
float a[]= { 1.123, 12.123, 123.123, 12345.123};
int i;
char floatString[100] = {0};
for (i=0; i < sizeof(a)/sizeof(a[0]); i++) {
memset(floatString, 0, sizeof(floatString));
sprintf(floatString, "%f", a[i]);
floatString[5] = ' ';
printf("%sn", floatString);
}
return 0;
}
你可以这样用,
printf("%1.3fn%2.2fn%3.1fn%5.0fn", a[0], a[1], a[2], a[3]);
可以这样使用snprintf
:
int main()
{
float a[]= { 1.123, 12.123, 123.123, 12345.123 };
char buf[8];
int i;
for (i=0;i<sizeof(a)/sizeof(a[0]);i++) {
snprintf(buf, 6, "%f", a[i]);
printf("%sn",buf);
}
}
相关文章:
- 0x%08lx 格式说明符在 printf 语句到 cout
- 了解 printf 格式规范中的 %03.3u
- 在没有格式说明符的情况下在c++中使用类似printf的实用程序
- 找到printf的意外错误,该格式为0.1F,用于四舍五入数字
- printf 的浮点格式标志 (%f) 仅适用于英文数字格式
- 在C 11 printf格式上寻求解释器,这些printf格式会消耗多个值
- 在CPP的COUT中等效的printf格式
- printf 格式说明符标志'0' %p,正确与否?
- 不正确的printf格式指定器编译
- 基于数据类型的printf格式
- 如何将 GCC 的 printf 格式属性与 C++11 可变参数模板一起使用?
- 一种在编译时用C++根据printf格式检查参数的可移植方法
- 将printf格式与iomanip匹配
- 在 Windows 上未签名__int64的 printf 格式
- 打印n个空格字符-(f)printf格式
- 从printf格式字符串中提取类型信息
- Python RE -正则表达式,用于匹配带有转义引号的类似printf格式字符串
- c++ /C int32_t和printf格式:%d或%ld
- 视觉C++:"float"的 printf() 格式规范是什么?
- 最大双宽度的Printf格式说明符