#include <stdio.h>
#include <stdlib.h>
char* float_to_string(float number, int precision) {
char *str = malloc(100 * sizeof(char)); // 为字符串分配足够的空间
if (str == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
int is_negative = number < 0;
if (is_negative) {
number = -number;
}
// 整数部分
long int_part = (long)number;
number -= int_part;
// 小数部分
for (int i = 0; i < precision; i++) {
number *= 10;
int_part += (long)number;
number -= (long)number;
}
// 转换整数部分为字符串
sprintf(str, "%ld", int_part);
// 添加小数点和小数部分
char *p = str + strlen(str);
*p++ = '.';
for (int i = 0; i < precision; i++) {
*p++ = '0' + ((int_part / (long)(pow(10, precision - i - 1))) % 10);
}
*p = '\0';
// 添加负号(如果需要)
if (is_negative) {
memmove(str + 1, str, strlen(str) + 1);
*str = '-';
}
return str;
}
int main() {
float num = -123.456;
int precision = 3;
char *str = float_to_string(num, precision);
printf("Converted string: %s\n", str);
free(str); // 释放分配的内存
return 0;
} |