[英]How to write .5 in printf in C?
I want to print 0.5 value in ".5" form in ANSI C? 我想在ANSI C中以“ .5”格式打印0.5值吗? I searched the web and stackoverflow, but I did not find what I want. 我搜索了网络和stackoverflow,但是没有找到想要的东西。 I tried both "%.1f" and "%0.1f ". 我尝试了“%.1f”和“%0.1f”。 But neiter of them worked. 但是他们中没有一个工作。
There is no such specification in C
to print fractional numbers without 0
at the begin. 在C
没有这样的规范来开始打印不带0
小数。 BTW you can use this code for your case: 顺便说一句,您可以在您的情况下使用以下代码:
printf(".%d", (int)(0.5*10));
Try this workaround: 尝试以下解决方法:
double f = 0.5;
printf(".%u\n" , (unsigned)((f + 0.05) * 10));
After accept answer 接受答案后
Should code need to avoid troubles with large floating point values, INF, NaN or edge conditions like 代码应该避免大浮点值,INF,NaN或边缘条件之类的麻烦
printf(".%d", (int)(0.46*10)); // prints "0.4"
Post-process the string. 后处理字符串。
void PrintdNoLead0(double x) {
const char *format = "%.1f\n";
if (fabs(x) < 1.0) {
char buf[10]; // Some buffer large enough for x in range -1<x<1
sprintf(buf, format, x);
char *p = strchr(&buf[1], '.');
if (p[-1] == '0') {
memmove(&p[-1], p, strlen(p));
}
fputs(buf, stdout);
} else {
printf(format, x);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.