如果自己写函数,不使用itoa怎么判断呢?
我们用通常的办法,对数字进行每位的除商,得到后与字符‘0‘相加。
flag = 0; for(i=0;i<6;i++){ tmp = int(num/pow(10,5-i)); if(tmp != 0){ *str = 1; flag = 1; } if(*str != 0 || flag){ *str++ = tmp+‘0‘; num = num%int(pow(10,5-i)); } }
要注意的就是,我们设置标志位flag,为1之前的所有0都不输出。当flag为1时,进行转换。
全部代码可以参考:
1 #include <stdio.h> 2 #include <stdlib.h> 3 //蔡健雅 双栖动物 4 int myitoa(int num,char *str,int n); 5 int pow(int num,int n); 6 int main(){ 7 int num = 100; 8 char str[15]; 9 myitoa(100,str,16); 10 printf("number %d binary %s\n",num,str); 11 myitoa(100,str,10); 12 printf("number %d binary %s\n",num,str); 13 myitoa(100,str,8); 14 printf("number %d binary %s\n",num,str); 15 myitoa(100,str,2); 16 printf("number %d binary %s\n",num,str); 17 getchar(); 18 return 0; 19 } 20 int pow(int num,int n){ 21 int i; 22 int result = 1; 23 for(i=0;i<n;i++){ 24 result *= num; 25 } 26 return result; 27 } 28 int myitoa(int num,char *str,int n){ 29 if(str == NULL) 30 return -1; 31 if(num < 0){ 32 *str++ = ‘-‘; 33 num = 0 - num; 34 } 35 int i; 36 int tmp = 0; 37 int flag = 0; 38 *str = 0; 39 switch(n){ 40 case 16: 41 flag = 0; 42 for(i=0;i<8;i++){ 43 tmp = int(num/pow(16,7-i)); 44 if(tmp != 0){ 45 *str = 1; 46 flag = 1; 47 } 48 if(*str != 0 || flag){ 49 if(tmp >= 0 && tmp <= 9){ 50 *str++ = tmp+‘0‘; 51 }else if(tmp >= 10 && tmp <= 15){ 52 *str++ = tmp-10+‘A‘; 53 } 54 num = num%int(pow(16,7-i)); 55 } 56 } 57 break; 58 case 10: 59 flag = 0; 60 for(i=0;i<6;i++){ 61 62 tmp = int(num/pow(10,5-i)); 63 if(tmp != 0){ 64 *str = 1; 65 flag = 1; 66 } 67 if(*str != 0 || flag){ 68 *str++ = tmp+‘0‘; 69 num = num%int(pow(10,5-i)); 70 } 71 } 72 break; 73 case 2: 74 flag = 0; 75 for(i=0;i<32;i++){ 76 tmp = int(num/pow(2,31-i)); 77 if(tmp != 0){ 78 *str = 1; 79 flag = 1; 80 } 81 if(*str != 0 || flag){ 82 *str++ = tmp+‘0‘; 83 num = num%int(pow(2,31-i)); 84 } 85 } 86 break; 87 case 8: 88 flag = 0; 89 for(i=0;i<10;i++){ 90 tmp = int(num/pow(8,9-i)); 91 if(tmp != 0){ 92 *str = 1; 93 flag = 1; 94 } 95 if(*str != 0 || flag){ 96 *str++ = tmp+‘0‘; 97 num = num%int(pow(8,9-i)); 98 } 99 } 100 break; 101 } 102 *str = ‘\0‘; 103 return 0; 104 }
运行结果为:
时间: 2024-12-25 13:34:37