吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言将浮点数转换为字符串

C语言将浮点数转换为字符串

来源:网络 | 更新时间:2022-01-30 14:36:34
编写一个 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”。
一种简单的方法是使用sprintf(),但不允许使用标准库函数进行直接转换。 方法:想法是将整数部分和小数部分分开,并将它们分别转换为字符串。以下是详细步骤。
  1. 从浮点数或双精度数中提取整数部分。
  2. 首先,将整数部分转换为字符串。
  3. 从 n 中按精确整数部分提取小数部分。
  4. 如果 d 不为零,则执行以下操作。
    1. 通过将小数部分乘以 pow(10, d) 将其转换为整数
    2. 将整数值转换为字符串并附加到结果中。
以下是上述方法的 C 实现。
// 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”
注意:如果采用双精度类型而不是浮点数,程序将执行类似的操作。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com