将整数转换成字符串的程序

来源:百度知道 编辑:UC知道 时间:2024/06/28 03:43:06
#include "stdio.h"
#include "conio.h"
int str[80];
void converttoch(long int m)
{
int i=0;
while(m>0)
{ str[i]=m%10+'0';
m/=10;
i++; }
str[i]='\0';
}
main()
{ long int n=123;

printf("Hello, world\n");
converttoch(n);
printf("\n%s",str);
getch();
}
无法达到预期结果,请高手指教。
不能使用其它函数,就用本题方法

//可以使用C库函数sprintf()来完成你的要求。下面的C代码段仅做参考。
<br>char str[80];
<br>void converttoch(long int m)
<br>{
<br> sprintf(str, "%d", m);
<br>}

//如果“不能使用其它函数,就用本题方法”,那么
1.将
int str[80];
改为
char str[80];
2.如果需要得到与整数“匹配”的字符串,那么还需要在converttoch()的末尾增加如下代码:
{ // 交换字符串前后顺序
char c;
int len = strlen(str);
int n = len / 2;
for(i = 0; i < n; i++)
{
c = str[i];
str[i] = str[len-1-i];
str[len-1-i] = c;
}
}

该程序中int str[80];应该改成char str[80];再倒序一下,
while(i>=0)
{
temp[j]=str[i];
j++;
i--;
}
temp[j]=0;
printf("%s\n",temp);
就可以了

其实不用那么复杂
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n;
char s[20];
n=123456;
itoa(n,s,10);