十进制转k进制的方法常用的就是除k取余的方法,
除二取余的方法,对于余数的选取是从后往前取的,所以在代码中,也要解决这个问题。
以二进制为列:
思路分析
模仿不停地除2的过程,每次除2之后用 % 取余数i;用 / 作为下一次除2的被除数temp;j初始化为1,每次除了2之后,j = j*10。最终输出的结果result在每次除2的迭代中,result = i*j + result;这个从后往前取余数的方法就是不断地result = i*j + result这样,不需要使用数组等方式逆序取了。
同时,也要考虑到十进制的负数如何转化,这里就是while(temp)来解决的。在while语句中,括号
内的值只要不是0就为真,这样就包含了负数的问题。
#include <iostream>
#include <string>
using namespace std;
int convert (int n, int base)//十进制转换为二进制或者八进制
{
int result = 0, temp = n, j = 1;
while (temp)
{
result = result + j * (temp % base);
temp = temp / base;
j = j * 10;
}
cout << result << endl;
return result;
}
string decimalToHex(int decimal)
{
string hex = "";
char hexChar[] = "0123456789ABCDEF";
while (decimal > 0)
{
int remainder = decimal % 16;
hex = hexChar[remainder] + hex;
decimal /= 16;
}
return hex;
}
int main()
{
int n;
cout << "请输入一个十进制整数:";
cin >> n;
cout << "二进制:";
convert(n, 2);
cout << "八进制:";
convert(n, 8);
cout << "十六进制:";
string hex = decimalToHex(n);
cout << hex << endl;
system("pause");
return 0;
}
(本人也是初学者,第一次写。方法可能比较复杂,佬轻喷!)