您的位置:首页 > 编程语言 > C语言/C++

[C/C++笔面试]不使用库函数将整数转换为字符串

2016-08-27 12:20 363 查看
C语言提供了将几个标准库函数,可以将任意类型的(整形、浮点型、长整形)的数字转换为字符串。

itoa():将整形值转换为字符串

ltoa();将长整形转换为字符串

ultoa();将无符号长整形转换为字符串

gcvt();将浮点数转换为字符串,取四舍五入

ecvt();将双精度浮点数转换为字符串,转换结果中不包含十进制小数点

fcvt();将指定位数转换精度

还可以使用sprintf系类函数把数字转换为字符串,这种方式比itoa系列函数速度慢

笔试面试的时候会经常遇到,不允许使用库函数将整数转换为字符串,如下

/*********************************************************
-  Copyright (C): 2016
-  File name    : int2str.c
-  Author       : - Zxn -
-  Date         : 2016年08月27日 星期六 11时16分06秒
-  Description  :

*  *******************************************************/
#include <stdio.h>

void int2str(int n, char *str)
{
char buf[10] = {0};       //临时数组
int i = 0;                //临时数组buf下标
int j = 0;                //str下标
int len = 0;
int temp = n < 0 ? -n: n; //取数字n的绝对值
//对负数做处理
if (n < 0)
{
str[j++] = '-';
}
//将数字倒序存放在临时数组
while (temp)
{
buf[i++] = temp % 10 + '0';
temp /= 10;
}
//完成转换
len = i - 1;
while (len >= 0)
{
str[j++] = buf[len--];
}
str[j] = '\0';
}

int main()
{
int num;
char p[10];

printf("please input an integer:");
scanf("%d", &num);

printf("output:");
int2str(num, p);
printf("%s\n", p);

return 0;
}


程序结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐