请帮我写一个C程序来解决我的问题。
问题-你在C中没有%f
,如何编写一个C程序来打印小数点后2位的小数而不使用%f
?
#include <stdio.h>
#include <math.h>
int main(void)
{
double num = 3.1416, a, b;
b = modf(num, &a) * 10000;
printf("%d.%dn", (int)a, (int)b);
return 0;
}
正如@mch指出的,它不适用于像3.04这样的数字,一个可行的解决方案(由Martin提供):
#include <stdio.h>
#include <math.h>
void dbl2str(char *s, double number, int decimals)
{
double integral, fractional, epsilon = 1e-9;
double round = 0.5 * pow(10, -decimals);
int n, i;
fractional = modf(number + round + epsilon, &integral);
n = sprintf(s, "%d%c", (int)integral, decimals ? '.' : 0);
for (i = 0; i < decimals; i++) {
fractional *= 10;
s[n + i] = '0' + (int)fractional;
fractional = modf(fractional, &integral);
}
s[n + i] = ' ';
}
int main(void)
{
char s[32];
dbl2str(s, 3.1416, 4);
printf("%sn", s);
dbl2str(s, 3.159, 4);
printf("%sn", s);
dbl2str(s, 3.05, 3);
printf("%sn", s);
return 0;
}
输出:3.1416
3.1590
3.050
为什么我们需要hack ?
如果你的浮点数据是单精度浮点格式
那我就用format specification
http://en.wikipedia.org/wiki/Single-precision_floating-point_format这里是32位浮点数
Sign bit: 1 bit
Exponent width: 8 bits
Significand precision: 24 bits (23 explicitly stored)
所以你可以解码这些东西并使用%d.%02d
打印显示整数和2小数
我会这样做:
float f = 23.48987;
int integerPart = (int)f; // integerPart = 23
int decimalPart = (int)(f*100 - integerPart*100); // decimalPart = 48
printf("%d.%02d", integerPart, decimalPart); // printed value - 23.48