#include <bits/stdc++.h> using namespace std; string jiafa(string s1, string s2) { string ans2 = ""; int t1, t2, ans1 = 0, up = 0; reverse(s1.begin(), s1.end()); reverse(s2.begin(), s2.end()); while (s1.length() != s2.length()) { if (s1.length() > s2.length()) s2 += '0'; else if (s1.length() < s2.length()) s1 += '0'; } cout << endl << s1 << endl << s2 << endl; for (int i = 0; i < s1.length() - 1; i++) { t1 = stoi(string(1, s1[i])); t2 = stoi(string(1, s1[i])); ans1 = t1 + t2 + up; if (ans1 >= 10) { ans1 %= 10; up = 1; } else up = 0; ans2 += static_cast<char>(ans1 + 48); } reverse(ans2.begin(), ans2.end()); return ans2; } int main() { string s1, s2; cin >> s1 >> s2; cout << jiafa(s1, s2); return 0; }纠正代码
时间: 2023-06-15 15:04:48 浏览: 129
下面是修改后的代码,主要是修正了变量t2的赋值错误,以及for循环中的终止条件错误:
```
#include <bits/stdc++.h>
using namespace std;
string jiafa(string s1, string s2) {
string ans2 = "";
int t1, t2, ans1 = 0, up = 0;
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
while (s1.length() != s2.length()) {
if (s1.length() > s2.length())
s2 += '0';
else if (s1.length() < s2.length())
s1 += '0';
}
cout << endl << s1 << endl << s2 << endl;
for (int i = 0; i < s1.length(); i++) {
t1 = stoi(string(1, s1[i]));
t2 = stoi(string(1, s2[i])); // 修改这里的赋值错误
ans1 = t1 + t2 + up;
if (ans1 >= 10) {
ans1 %= 10;
up = 1;
} else
up = 0;
ans2 += static_cast<char>(ans1 + 48);
}
reverse(ans2.begin(), ans2.end());
return ans2;
}
int main() {
string s1, s2;
cin >> s1 >> s2;
cout << jiafa(s1, s2);
return 0;
}
```
阅读全文