1 //1.10数制转换 2 //给定一个M进制的数x,实现对x向任意的一个非M进制的数的转换 3 #include<stdio.h> 4 #define MAXCHAR 101 5 //字符转换为数字 6 int char_to_num(char ch); 7 //数字转换为字符 8 char num_to_char(int num); 9 //其它进制转换为十进制 10 long source_to_decimal(char temp[],int source); 11 //十进制转换为其他进制 12 int decimal_to_object(char temp[],long decimal,int object); 13 //转换后新数输出 14 void output(char temp[],int length); 15 16 void main() 17 { 18 int source; 19 int object; 20 int length; 21 long decimal_num; 22 char temp[MAXCHAR]; 23 int flag=1; 24 while(flag) 25 { 26 printf("转换前的数是:"); 27 scanf("%s",temp); 28 printf("转换前的数制是:"); 29 scanf("%d",&source); 30 printf("转换后的数制是:"); 31 scanf("%d",&object); 32 printf("转换后的数是:"); 33 decimal_num = source_to_decimal(temp,source); 34 length = decimal_to_object(temp,decimal_num,object); 35 output(temp,length); 36 printf("继续请输入1,否则输入0:\n;"); 37 scanf("%d",&flag); 38 } 39 } 40 41 int char_to_num(char ch) 42 { 43 if(ch>='0' && ch<='9') 44 return ch-'0'; 45 else 46 return ch-'A'+10; 47 } 48 49 char num_to_char(int num) 50 { 51 if(num>=0 && num<=9) 52 return (char)('0'+num-0); 53 else 54 return (char)('A'+num-10); 55 } 56 57 long source_to_decimal(char temp[],int source) 58 { 59 long decimal_num = 0; 60 int length; 61 int i; 62 for(i=0;temp[i]!='\0';i++); 63 length = i; 64 for(i=0;i<=length-1;i++) 65 decimal_num = (decimal_num * source) + char_to_num(temp[i]); 66 return decimal_num; 67 } 68 69 int decimal_to_object(char temp[],long decimal_num,int object) 70 { 71 int i; 72 while(decimal_num) 73 { 74 temp[i] = num_to_char(decimal_num%object); 75 decimal_num = decimal_num/object; 76 i++; 77 } 78 temp[i] = '\0'; 79 return i; 80 } 81 82 void output(char temp[],int length) 83 { 84 int i; 85 for(i=length-1;i>=0;i--) 86 printf("%c",temp[i]); 87 printf("\n"); 88 }
标签:20,temp,int,decimal,printf,char,num,2023.4 From: https://www.cnblogs.com/muzhaodi/p/17338553.html