當一個數的基數是負數時,將這個數轉換為負進制數時,大體思路和正數的情況一樣,但是因為基數是負數,所以計算出來的余數就有可能是負數所以,需要在余數是負數時:將余數 + 基數的絕對值,商 + 1。
代碼如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;int main() {int n, R;
//R為基數,輸入保證一定為負數cin >> n >> R;int m = n;vector<int> a;while(n) {int x = n % R;//余數int y = n / R;//商if(x < 0) {x = x + abs(R);y ++;}n = y;a.push_back(x);}reverse(a.begin(), a.end());cout << m << '=';for(int i = 0; i < a.size(); i ++){if(a[i] > 9) {char c = a[i] - 10 + 'A';cout << c;}else {cout << a[i];}} cout << "(base" << R << ")"; return 0;
}