C++实现十进制转换为任意进制

  1. 十进制数在C++中用什么表示?
  2. 一个十进制数,在程序中用什么方式转换为其他进制,和在数学中的思路一样吗??
  3. 输出的结果用什么表示比较方便?
  4. 下面的程序中digit思考为什么要用静态变量?
#include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;

class Solution {
public:
	void ConvertRes(stack<char>& s, __int64 n, int base);
	void ConvertIteration(stack<char>& s, __int64 n, int base);
};

int main()
{
	Solution sol;
	stack<char> s;
	int num = 0;//十进制
	int sys = 0;//转换后的进制
	cin >> num >> sys;
	sol.ConvertRes(s, num, sys);
	while (!s.empty())
	{
		cout << s.top();
		s.pop();
	}
	cout << endl;
	system("pause");
	return 0;
}

//递归实现
void Solution::ConvertRes(stack<char>& s, __int64 n, int base)
{
	static char digit[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };//新进制下的数位
	if (n > 0)//直到n->0
	{
		s.push(digit[n%base]);//存入
		ConvertRes(s, n / base, base);//第二个参数十进制数更新,通过递归得到所有更高位
	}
}

//迭代实现
void Solution::ConvertIteration(stack<char>& s, __int64 n, int base)
{
	static char digit[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };//新进制下的数位
	while (n > 0)
	{
		int remainder = int(n%base);
		s.push(digit[remainder]);
		n /= base;
	}
}

 

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
以下是一个将任意进制数转换为任意进制数的 C++ 代码示例: ```cpp #include <iostream> #include <string> using namespace std; // 将任意进制数转换为进制数 int toDecimal(string num, int base) { int result = 0; int power = 1; int len = num.size(); for (int i = len - 1; i >= 0; i--) { int digit = isdigit(num[i]) ? num[i] - '0' : num[i] - 'A' + 10; if (digit >= base) { cout << "非法输入!" << endl; return -1; } result += digit * power; power *= base; } return result; } // 将进制数转换为任意进制数 string fromDecimal(int num, int base) { string result = ""; while (num > 0) { int digit = num % base; char ch = (digit >= 10) ? ('A' + digit - 10) : (digit + '0'); result = ch + result; num /= base; } return result; } // 主函数 int main() { string num; int base1, base2; cout << "请输入要转换的数字:"; cin >> num; cout << "请输入数字的原始进制:"; cin >> base1; cout << "请输入数字要转换的进制:"; cin >> base2; int decimal = toDecimal(num, base1); if (decimal == -1) { return 0; } string result = fromDecimal(decimal, base2); cout << num << "(" << base1 << "进制) = " << result << "(" << base2 << "进制)" << endl; return 0; } ``` 该程序首先要求用户输入要转换的数字、数字的原始进制和数字要转换的进制。然后,它将使用 `toDecimal` 函数将数字从原始进制转换进制,并使用 `fromDecimal` 函数将其转换为指定的进制。最后,程序将打印转换后的数字。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值