思想:
1.用短除法像处理正常进制一样将所有余数算出来 //余数转化为正数
2. 负数转化公式:
被除数=商*除数+余数
=商*除数+除数-除数+余数
=除数*(商+1)+(余数-除数)
举个例子:
-7(十进制)转化为 (-2进制)
7/-2=3+(-1);
因为3+1=4,-1-(-2)=1;
所以7/-2=4*-2+1;
成功将余数转化为正数
#include <iostream>
using namespace std;
string transfer(int num, int base)
{
if (num == 0)
return "0";
string ans = "";
while (num != 0)
{
int reminder = num % base;
num /= base;
if (reminder < 0)
{
num++;
reminder -= base;
}
char cur = (reminder >= 10 ? ('A' + reminder - 10) : (reminder + '0'));
ans = cur + ans;
}
return ans;
}
int main()
{
int N, base;
cin >> N >> base;
string ans = transfer(N, base);
cout << N << "=" << ans << "(base" << base << ")" << endl;
system("pause");
return 0;
}
标签:num,进制,转化,base,ans,余数,reminder,除数
From: https://blog.csdn.net/2303_79639713/article/details/137553451