编写一个 C 函数 ftoa() 将给定的浮点数或双精度数转换为字符串。不允许使用标准库函数进行直接转换。下面是 ftoa() 的原型。本文提供了将 C double 转换为字符串的见解。
ftoa(n, res, afterpoint) n --> 输入数字 res[] --> 要存储输出字符串的数组 afterpoint --> 在该点之后要考虑的位数。例子:
- ftoa(1.555, str, 2) 应该在 res 中存储“1.55”。
- ftoa(1.555, str, 0) 应该在 res 中存储“1”。
- 从浮点数或双精度数中提取整数部分。
- 首先,将整数部分转换为字符串。
- 从 n 中按精确整数部分提取小数部分。
- 如果 d 不为零,则执行以下操作。
- 通过将小数部分乘以 pow(10, d) 将其转换为整数
- 将整数值转换为字符串并附加到结果中。
// C program for implementation of ftoa()
#include <math.h>
#include <stdio.h>
// Reverses a string 'str' of length 'len'
void reverse(char* str, int len)
{
int i = 0, j = len - 1, temp;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
// Converts a given integer x to string str[].
// d is the number of digits required in the output.
// If d is more than the number of digits in x,
// then 0s are added at the beginning.
int intToStr(int x, char str[], int d)
{
int i = 0;
while (x) {
str[i++] = (x % 10) + '0';
x = x / 10;
}
// If number of digits required is more, then
// add 0s at the beginning
while (i < d)
str[i++] = '0';
reverse(str, i);
str[i] = ' ';
return i;
}
// Converts a floating-point/double number to a string.
void ftoa(float n, char* res, int afterpoint)
{
// Extract integer part
int ipart = (int)n;
// Extract floating part
float fpart = n - (float)ipart;
// convert integer part to string
int i = intToStr(ipart, res, 0);
// check for display option after point
if (afterpoint != 0) {
res[i] = '.'; // add dot
// Get the value of fraction part upto given no.
// of points after dot. The third parameter
// is needed to handle cases like 233.007
fpart = fpart * pow(10, afterpoint);
intToStr((int)fpart, res + i + 1, afterpoint);
}
}
// Driver program to test above function
int main()
{
char res[20];
float n = 233.007;
ftoa(n, res, 4);
printf(""%s"n", res);
return 0;
}
输出:
注意:如果采用双精度类型而不是浮点数,程序将执行类似的操作。 “233.0070”