写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。
#include<stdio.h> #include<stdlib.h> void itob(int n, char s[],int b)//整数n转换为以b进制的数 { int i = 0; int start = 0; int end = 0; if ((b == 2) || (b == 8))//2进制和8进制 { while (n) { s[i] = n%b + ‘0‘; n = n / b; i++; } } else if (b == 16)//16进制 { while (n) { s[i] = "0123456789abcdef"[n%16]; char*p="0123456789abcdef"; s[i]=p[n%16]; 即*(p+(N%16)) n = n / 16; i++; } } end = i - 1; while (start < end) { char tmp = s[start]; s[start] = s[end]; s[end] = tmp; start++; end--; } s[i] = ‘\0‘; } int main() { char arr[32]; int n = 0; int b = 0; printf("数字:"); scanf("%d", &n); printf("进制:"); scanf("%d", &b); itob(n, arr, b); printf("\n%s\n",arr); system("pause"); return 0; }
本文出自 “无以伦比的暖阳” 博客,请务必保留此出处http://10797127.blog.51cto.com/10787127/1716183
原文地址:http://10797127.blog.51cto.com/10787127/1716183