BinarySystem()是將二進制數字轉換成十進制
第13行:Bin[i]-48是因為Bin是字元(char),所以要透過ASCII(美國資訊交換標準碼)轉換成數字。
#include<iostream>
#include<conio.h>
void BinarySystem(){
char Bin[11];
int LastDigit=0;
int Decimal=0, Weight=1;
printf("請輸入二進制數字(最多10位元):");
scanf("%s", Bin);
while(Bin[LastDigit]!='\0')
LastDigit++;
LastDigit--;
for(int i=LastDigit; i>=0; i--){
Decimal=Decimal+(Bin[i]-48)*Weight;
Weight*=2;
}
printf("二進制數字:%s\n十進制數字:%d\n", Bin, Decimal);
}
OctalSystem()是將八進制數字轉換成十進制
void OctalSystem(){
char Bin[11];
int LastDigit=0;
int Decimal=0, Weight=1;
printf("請輸入八進制數字(最多10位元):");
scanf("%s", Bin);
while(Bin[LastDigit]!='\0')
LastDigit++;
LastDigit--;
for(int i=LastDigit; i>=0; i--){
Decimal=Decimal+(Bin[i]-48)*Weight;
Weight*=8;
}
printf("八進制數字:%s\n十進制數字:%d\n", Bin, Decimal);
}
HexSystem()是將十六進制數字轉換成十進制
第43行:因為十六進制有A、B、C、D、E、F因此需要更改ASCII轉換成數字的參數
void HexSystem(){
char Bin[11];
int LastDigit=0;
int Decimal=0, Weight=1;
printf("請輸入十六進制數字(最多10位元,字母請大寫):\n");
scanf("%s", Bin);
while(Bin[LastDigit]!='\0')
LastDigit++;
LastDigit--;
for(int i=LastDigit; i>=0; i--){
if(Bin[i]>=65)
Decimal=Decimal+(Bin[i]-55)*Weight;
else
Decimal=Decimal+(Bin[i]-48)*Weight;
Weight*=16;
}
printf("十六進制數字:%s\n十進制數字 :%d\n", Bin, Decimal);
}
選擇轉換模式
void SelectMode(){
char Mode;
printf("選擇模式:A.二進位; B.八進位; C.十六進位;\n");
Mode=_getche();
printf("\n");
if(Mode=='A')
BinarySystem();
else if(Mode=='B')
OctalSystem();
else if(Mode=='C')
HexSystem();
else{
printf("沒有這種模式!\n");
}
}
主程式,利用do-while的方式重複做。
int main(){
char Choose;
printf("數字系統:轉換成十進位");
do{
SelectMode();
printf("是否要重作?(Y/N)\n");
Choose=_getche();
printf("\n");
}while(Choose=='Y' || Choose=='y');
system("pause");
return 0;
}
因為當中有十六進制,所以採用字元(char)的放式儲存變數。
雖然比使用數學運算式來的耗資源,但是用字元(char)更方便看懂計算過程。
No comments:
Post a Comment