对于定点,只需在除法前将分子乘以 10。对于浮点,只需使用除法然后modf 即可获得小数部分。在任何一种情况下,转换为字符串,然后格式化为首选格式(1 个十进制)。
在 C 语言中,您可以使用 _Generic 来处理定点或浮点的通用处理。
没有任何错误处理的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char* strfract_int (char* dst, int n, int d)
{
sprintf(dst, "0.%d", n*10 / d);
return dst;
}
char* strfract_double (char* dst, double n, double d)
{
double dummy;
sprintf(dst, "%.1f", modf(n/d, &dummy) );
return dst;
}
#define strfract(dst, n, d) \
_Generic((n), \
int: strfract_int, \
double: strfract_double)(dst,n,d) \
int main (void)
{
char buf [100];
puts( strfract(buf, 1, 3) );
puts( strfract(buf, 2, 5) );
puts( strfract(buf, 1.0, 3.0) );
puts( strfract(buf, 2.0, 5.0) );
}
在一个坚固的程序中,检查除零、malloc 等的结果等。