【B1022/模拟】D进制的A+B(进制转换)

思路:这道题做法和B1016 部分A+B类似,但要注意最后要将数字逆序输出,故最好用数组存储每一位数字。数组长度不能直接得到,故可以用一个计数器边输入边累加。

下面这个做法不能处理最高位为0的情况,所以一定在最开始就边处理边用数组存下每一位,而不是冗余处理

#include<iostream>
#include<cmath>
using namespace std;
int main() {
	int a, b, c, d, ans = 0, res[110] = { 0 };
	cin >> a >> b>>d;
	c = a + b;
	while (c != 0) {
		int db = c % d;
		c /= d;
		ans = ans * 10 + db;
	}
	if (ans == 0)	cout << 0;
	int i = 0;
	while (ans != 0) {
		int db = ans % 10;
		res[i] = db;
		ans /= 10;
		i++;
	}
	for (int j = 0; j < i; j++)
		cout << res[j];
	system("pause");
	return 0;
}
#include<iostream>
#include<cmath>
using namespace std;
int main() {
	int a, b, c, d,res[110] = { 0 };
	bool flag = false;
	cin >> a >> b>>d;
	c = a + b;
	int i = 0;
	while (c != 0) {
		int db = c % d;
		c /= d;
		res[i++] = db;
		flag = true;
	}
	if (flag == false)	cout << 0;
	for (int j = i-1; j >=0; j--)
		cout << res[j];
	system("pause");
	return 0;
}

今天又学到一个提取数字每一位的方法->将数字当做字符串输入:

#include<iostream>
#include<string>
using namespace std;
int main() {
	int res[110] = { 0 };
	string s;
	cin>>s;
	for(int i=0;i<s.length();i++){
		res[i]=s[i]-'0';
		cout<<res[i]<<" ";
	}
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值