思路:这道题做法和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;
}