極簡·十進制轉其他進制

一、實驗目的

將十進制數轉化爲其他進制的數

二、實驗過程

2.1 C/C++

使用自帶函數

itoa(num,str,n);
  • num 十進制數
  • str char數組,用來存儲結果
  • n 代表準備轉換的進制

int num  = 15;

char str[30];

//將15轉爲2進制
itoa(num , str, 2);

//將15轉爲16進制
itoa(num , str, 16);

完整代碼

#include<stdio.h>
#include<stdlib.h>
//注意必須調用stdlib.h函數庫
int main(void) {
	int a;
	scanf("%d",&a);
	char str[30];
	
	itoa(a,str,2);
	printf("%s\n",str);

	itoa(a,str,16);
	printf("%s\n",str);
	return 0;
}

運行結果

2.2 Python

使用自帶函數 bin(),oct(),hex()
示例代碼

x = 15

print("{0}的二進制值爲:{1}".format(x, bin(x)))

print("{0}的八進制值爲:{1}".format(x, oct(x)))

print("{0}的十六進制值爲:{1}".format(x, hex(x)))


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章