C語言實現整數的通用進位制轉換
阿新 • • 發佈:2019-02-08
/*
* 檔名:baseConvert.c
* 功能描述:實現將10進位制整數轉換為進位制大於1的數
* 編輯人:王廷雲
* 編輯日期:2017-1-1
*/
#include <stdio.h>
void convertBase(int num, int base); // 通用進位制轉換函式
/* 從主函式開始 */
int main(void)
{
int num;
int base; // 需要轉換的進位制
fprintf(stdout, "請輸入需要轉換的正整數:");
/* 獲取使用者需要轉換的正整數 */
while (1)
{
if (fscanf(stdin, "%d", &num) != 1) // 檢查輸入是否為整數
{
fprintf(stderr, "輸入錯誤!請輸入正整數:");
while (getchar() != '\n'); // 去掉多餘的非法字元
continue;
}
else if (num < 0) // 檢查輸入是否為正數
{
fprintf(stderr, "輸入錯誤!請輸入正整數:");
continue ;
}
else
{
break;
}
}
/* 獲取使用者需要轉換的進位制 */
fprintf(stdout, "請輸入需要轉換的進位制(大於1):");
fflush(stdout); // 為了避免緩衝區的bug而及時刷出
while(1)
{
if (fscanf(stdin, "%d", &base) != 1) // 檢查輸入是否為整數
{
fprintf(stderr, "輸入錯誤!請輸入正確的進位制(大於1):" );
fflush(stdout);
while (getchar() != '\n'); // 去掉多餘的非法字元
continue;
}
else if (base <= 1) // 進位制必須大於1
{
fprintf(stderr, "輸入錯誤!請輸入正確的進位制(大於1):");
while (getchar() != '\n'); // 去掉多餘的非法字元
continue;
}
else
{
break;
}
}
/* 呼叫轉換函式並列印結果 */
fprintf(stdout,"10進位制數%d轉換為%d進位制數為: ", num, base);
convertBase(num,base);
fputc('\n', stdout);
return 0;
}
/*
* 函式名:convertBase
* 函式功能:把10進位制數轉換為指定的進位制數
* 引數:1.需要轉換的10進位制整數 2.需要轉換的進位制
* 返回值:無
*/
void convertBase(int num, int base)
{
/* 第歸結束條件 */
if (num == 0)
{
return;
}
else
{
convertBase(num/base, base);
}
/* 列印結果 */
if (base == 16) // 處理16進位制的特殊情況:16進位制包含字母
{
fputc("0123456789abcdef"[num%base], stdout);
}
else // 其它進位制:直接列印
{
fprintf(stdout, "%d", num%base);
}
}