标签:fabs return number its button switch index ring printf
目前只能实现简单的功能
1 #include <stdio.h> 2 #include <limits.h> 3 #include <math.h> 4 #include <string.h> 5 #include <stdlib.h> 6 #include <ctype.h> 7 int size; 8 char string[CHAR_BIT * sizeof(int) + 1]; 9 void change_to_16(void) 10 { 11 printf("0x"); 12 for (int j = 0, index = 0, count = 0, k = 0; j <size; j++, index++) 13 { 14 if (index == 0) count += (string[j] - ‘0‘) * 8; 15 if (index == 1) count += (string[j] - ‘0‘) * 4; 16 if (index == 2) count += (string[j] - ‘0‘) * 2; 17 if (index == 3) 18 { 19 count += (string[j] - ‘0‘); 20 if (count < 10) printf("%d", count); 21 else 22 { 23 switch (count) 24 { 25 case 10:printf("a"); break; 26 case 11:printf("b"); break; 27 case 12:printf("c"); break; 28 case 13:printf("d"); break; 29 case 14:printf("e"); break; 30 case 15:printf("f"); break; 31 } 32 } 33 index = -1; 34 count = 0; 35 } 36 } 37 } 38 void change_to_8(void) 39 { 40 printf("0"); 41 char string8[1000] = { 0 }; 42 for (int j = size - 1, index = 0, count = 0, k = 0; j >= 0; j--, index++) 43 { 44 if (index == 0) count += string[j] - ‘0‘; 45 if (index == 1) count += (string[j] - ‘0‘) * 2; 46 if (index == 2) 47 { 48 count += (string[j] - ‘0‘) * 4; 49 string8[k++] = count + ‘0‘; 50 index = -1; 51 count = 0; 52 } 53 } 54 int len = strlen(string8); 55 for (int i = len - 1; i >= 0; i--) 56 printf("%c", string8[i]); 57 } 58 void change_to_2(void) 59 { 60 int j = 0; 61 while (string[j]) 62 { 63 putchar(string[j]); 64 if (++j % 4 == 0 && string[j]) 65 putchar(‘ ‘); 66 } 67 } 68 int main(void) 69 { 70 int number; 71 char button; 72 printf("choose the mode:\n"); 73 printf("A,to binary\nB,to octal\nC,to hexadecimal\n"); 74 scanf("%c", &button); 75 button = toupper(button); 76 fflush(stdin); 77 printf("Enter a decimal number:"); 78 while (~scanf("%d", &number)) 79 { 80 if (fabs(number) <= 15) size = 4; 81 else if (fabs(number) < 256&&fabs(number)>15) size = 8; 82 else if (fabs(number) >= 256 && fabs(number) < 4096) size = 12; 83 else if (fabs(number) >= 4096 && fabs(number) < 65536) size = 16; 84 else size = 20; 85 for (int i = size - 1; i >= 0; i--, number >>= 1) 86 string[i] = (01 & number) + ‘0‘; 87 string[size] = ‘\0‘; 88 switch (button) 89 { 90 case ‘A‘:change_to_2(); break; 91 case ‘B‘:change_to_8(); break; 92 case ‘C‘:change_to_16(); break; 93 } 94 putchar(‘\n‘); 95 printf("Enter a decimal number:"); 96 } 97 return 0; 98 }
标签:fabs return number its button switch index ring printf
原文地址:http://www.cnblogs.com/ray-coding-in-rays/p/6165836.html