Data_Structure/作業/test/double_pointer.cpp
2025-01-20 21:30:53 +08:00

66 lines
1.4 KiB
C++

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void convert(int n, int b, char **result, int *size) {
// 計算需要的位數
int temp = n;
*size = 0;
while (temp > 0) {
temp /= b;
(*size)++;
}
// 配置記憶體
*result = (char*)malloc((*size + 1) * sizeof(char));
if (*result == NULL) {
printf("記憶體配置失敗!\n");
return;
}
// 進行轉換
int i = *size - 1;
while (n > 0) {
int remainder = n % b;
if (remainder < 10) {
(*result)[i] = remainder + '0';
} else {
(*result)[i] = (remainder - 10) + 'A';
}
n /= b;
i--;
}
(*result)[*size] = '\0'; // 添加字串結尾
}
int main() {
int n, b;
char *result; // 用來存放轉換結果的指標
int size; // 結果的長度
while(1) {
printf("\n輸入待轉換的十進位正整數 ==> ");
scanf("%d", &n);
if(n == -1) break;
printf("\n輸入轉換之基底 ==> ");
scanf("%d", &b);
convert(n, b, &result, &size); // 傳入指標的位址
printf("(%d)_10 = (", n);
for(int i = 0; i < size; i++) {
printf("%c", result[i]);
}
printf(")_%d\n", b);
free(result); // 釋放配置的記憶體
}
printf("程式將結束...按任意鍵繼續\n");
system("pause");
return 0;
}