这道题目,我是在自己写的练习3-4的程序的基础上进行修改的:
#include <stdio.h>
#include <limits.h>
void itoa(int n, char s[], int m);
void reverse(char s[]);
int main(){
int n;
char s[100];
n=INT_MIN;
itoa(n,s,15);
for(int i=0;s[i]!='\0';++i){
printf("%c",s[i]);
}
printf("\n");
n=123456789;
itoa(n,s,15);
for(int i=0;s[i]!='\0';++i){
printf("%c",s[i]);
}
return 0;
}
void itoa(int n, char s[],int m)
{
int i=0;
int sign=n;
unsigned n_copy;
if ((sign=n)<0){
if((n-1)>0){
n_copy=n;
}else{
n_copy = -n;
}
}else{
n_copy=n;
}
do {
s[i++] = n_copy % 10 + '0';
} while ((n_copy /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
if(i<m){
for(int j=i;j>=0;--j){
s[j+m-i]=s[j];
}
for(int j=m-i-1;j>=0;--j){
s[j]=' ';
}
}
}
void reverse(char s[]){
int i;
for(i=0;s[i]!='\0';++i){
;
}
--i;
for(int j=0;i>j;--i,++j){
char temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
执行结果如下图所示: