a+b a-b
2023-08-15 15:19:09
发布于:广东
6阅读
0回复
0点赞
a+b:
#include<bits/stdc++.h>
using namespace std;
char s1[505],s2[505];
int a[505],b[505],c[505];
int main(){
int la,lb,lc;
scanf("%s",s1);
scanf("%s",s2);
la=strlen(s1);
lb=strlen(s2);
for(int i=0;i<la;i++)
{
a[la-i]=s1[i]-'0';
}
for(int i=0;i<lb;i++)
{
b[lb-i]=s2[i]-'0';
}
lc=max(la,lb)+1;
for(int i=1;i<=lc;i++)
{
c[i]+=a[i]+b[i];
c[i+1]=c[i]/10;
c[i]=c[i]%10;
}
if(c[lc]==0 && lc>0) lc--;
for(int i=lc;i>0;i--)
cout<<c[i];
return 0;
}
a-b:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int len1, len2;
int a[maxn], b[maxn];
string s1, s2;
void swap(string &a, string &b){
string t;
t = a;
a = b;
b = t;
}
bool compare(string a, string b){
if (a.size() < b.size()) return true; //当a的位数比b小时,a比b小
if (a.size() > b.size()) return false; //当a的位数比b大时,a比b大
for (int i = 0; i < a.size(); ++i) //剩余情况就是a的位数与b相同
{
if (a[i] > b[i]) return false; //逐位比较
if (b[i] > a[i]) return true;
}
return false; //最后当a与b的各个位的数字都相同时,a等于b
}
int main()
{
cin >> s1;
cin >> s2;
if (compare(s1, s2)){
swap(s1, s2);
putchar('-');
}
len1 = s1.size();
len2 = s2.size();
for (int i = 0; i < len1; ++i) a[len1 - i] = s1[i] - '0';
for (int i = 0; i < len2; ++i) b[len2 - i] = s2[i] - '0';
for (int i = 1; i <= len1; ++i){
a[i] -= b[i];
if (a[i] < 0) {
a[i + 1]--; //就向高位借一
a[i] += 10;
}
}
while (a[len1] == 0 && len1 > 1) len1--;
for (int i = len1; i >= 1; --i) printf("%d", a[i]);
return 0;
}
这里空空如也
有帮助,赞一个