《c程序设计语言》读书笔记-3.6-数字转字符串最小宽度限制
#include <io.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> void reverse(char s[]) { int c,i,j; for(i = 0,j = strlen(s) - 1;i < j;i++,j--) c = s[i],s[i] = s[j],s[j] = c; } void itoa(int n,char s[],int max) { int i,sign; sign = n,i = 0; do { s[i++] = abs(n % 10) + '0'; }while((n /= 10) != 0); if(sign < 0) s[i++] = '-'; while(i < max) s[i++] = ' '; s[i] = '\0'; reverse(s); } int main() { int n,i; char s[50]; int max = 10; n = -2; itoa(n,s,max); for(i = 0;i < strlen(s);i++) printf("%c ",s[i]); return 0; }