輸入兩個非負 10 進制整數 A 和 B (≤),輸出 A+B 的 D (1)進制數。html
輸入在一行中依次給出 3 個整數 A、B 和 D。ios
輸出 A+B 的 D 進制數。flex
123 456 8
1103
給定一個2進制數1011,將其轉成10進制: $1*10^3 + 1*10^2 +0*10^1+1*10^0$ = 11spa
C++實現:code
1 // P進制轉10進制 2 int PtoTen(int x, int P) 3 { 4 int result = 0; 5 int product = 1; 6 while (x != 0) 7 { 8 result = result + (x % 10) * product; 9 x = x / 10; 10 product = product * P; 11 } 12 return result; 13 }
採用「除基(Q)取餘法」
htm
給定一個10進制數:17,將其轉成2進制blog
17 / 2 = 8, 餘1ci
8 / 2 = 4 餘0get
4 / 2 = 2 餘0it
2 / 2 = 1 餘0
1 / 2 = 0 餘1
計算結束
接着將餘數從後往前(從下往上)輸出,獲得的10001就是17的二進制數
C++實現
1 // 10進制轉Q進制 2 void tenToQ(int x, int Q) 3 { 4 vector<int> left; //保存餘數 5 do 6 { 7 left.push_back(x % Q); 8 x /= Q; 9 } while (x != 0); 10 //反向輸出餘數 11 for (auto it = left.rbegin(); it != left.rend(); ++it) 12 { 13 cout << *it; 14 } 15 }
注意:用do while是由於,若是10進制數剛好等於0,應該輸出餘數0,若是是while循環,則不會保存餘數
將A和B相加,再按照上面的內容轉化成D進制就能夠了
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 void tenToQ(int x, int Q) 6 { 7 vector<int> left; 8 do 9 { 10 left.push_back(x % Q); 11 x /= Q; 12 } while (x != 0); 13 14 for (auto it = left.rbegin(); it != left.rend(); ++it) 15 { 16 cout << *it; 17 } 18 } 19 20 int main() 21 { 22 int A, B, D; 23 cin >> A >> B >> D; 24 tenToQ(A + B, D); 25 return 0; 26 }