問題描述
練習 3-5 編寫函式 itob(n, s, b),將整數n轉換為以b為底的數,並將轉換結果以字元的形式儲存到字串s中。例如,itob(n, s, 16)把整數n格式化成十六進位制整數儲存在s中。
Write the function itob(n,s,b)
that converts the integer n
into a base b
character representation in the string s
. In particular, itob(n,s,16)
formats n
as a hexadecimal integer in s
.
程式碼如下
#include<stdio.h> #include<string.h> void reverse(char s[])//字串倒置函式 { int i,j,t; for ( i = 0,j=strlen(s)-1; i <j; i++,j--) { t = s[i]; s[i] = s[j]; s[j] = t; } } void itob(int n,char s[],int b) { int sign,i; static char b_numbers[]={"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; if ((sign=n)<0) { n = -n; } i=0; do { s[i++] = b_numbers[n % b]; } while ((n/=b)>0); if (sign<0) { s[i++]='-'; } s[i]='\0'; reverse(s); } int main() { char array[100]; int n,b; printf("請輸入要轉換的十進位制數:"); scanf("%d",&n); putchar('\n'); printf("轉換為多少進位制:"); scanf("%d",&b); putchar('\n'); itob(n,array,b); printf("結果為:"); for (int i = 0; array[i]!='\0'; i++) { printf("%c",array[i]); } putchar('\n'); return 0; }
執行結果