https://www.luogu.com.cn/problem/P1957
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int ws(int);
void jia();
void jian();
void cheng();
int n, length;
string a;
int main() {
cin >> n;
while(n-- >= 0) {
getline(cin, a);
length = a.length();
if(isdigit(a[0]) || a[0] == 'a')
jia();
else if(a[0] == 'b')
jian();
else if(a[0] == 'c')
cheng();
}
return 0;
}
int ws(int x) {
int w = 0;
if(x < 0) {
x = abs(x);
w++;
}
while(x > 0) {
x /= 10;
w++;
}
return w;
}
void jia() {
int i = 0, js = 0, bjs = 0;
if(!isdigit(a[i]))
i += 2;
while(a[i] != ' ') {
bjs *= 10;
bjs += a[i] - '0';
i++;
}
i++;
while(i < length) {
js *= 10;
js += a[i] - '0';
i++;
}
int h = bjs + js;
int l = ws(bjs) + ws(js) + ws(h) + 2;
printf("%d+%d=%d\n%d\n", bjs, js, h, l);
return ;
}
void jian() {
int i = 0, js = 0, bjs = 0;
if(!isdigit(a[i]))
i += 2;
while(a[i] != ' ') {
bjs *= 10;
bjs += a[i] - '0';
i++;
}
i++;
while(i < length) {
js *= 10;
js += a[i] - '0';
i++;
}
int h = bjs - js;
int l = ws(bjs) + ws(js) + ws(h) + 2;
printf("%d-%d=%d\n%d\n", bjs, js, h, l);
return ;
}
void cheng() {
int i = 0, cs = 0, bcs = 0;
if(!isdigit(a[i]))
i += 2;
while(a[i] != ' ') {
bcs *= 10;
bcs += a[i] - '0';
i++;
}
i++;
while(i < length) {
cs *= 10;
cs += a[i] - '0';
i++;
}
int h = bcs * cs;
int l = ws(bcs) + ws(cs) + ws(h) + 2;
printf("%d*%d=%d\n%d\n", bcs, cs, h, l);
return ;
}
代码修改如下,供参考:
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int ws(int);
void operation(string a,char ch);
int main()
{
int n, i = 0;
string a;
char ch;
cin >> n;
cin.get();
while (n--) {
getline(cin, a);
if (a[0] == 'a') {
ch = '+';
}
else if (a[0] == 'b') {
ch = '-';
}
else if (a[0] == 'c') {
ch = '*';
}
else if (i == 0)
continue;
operation(a, ch);
i++;
}
return 0;
}
int ws(int x) {
int w = 0;
if (x < 0) {
x = abs(x);
w++;
}
while (x > 0) {
x /= 10;
w++;
}
return w;
}
void operation(string a,char ch)
{
int i = 0, flg = 0, js = 0, bjs = 0, tmp = 0;
while (i < a.length())
{
if (isdigit(a[i]))
{
flg = 1;
while (isdigit(a[i]) && i < a.length()) {
js = js * 10 + a[i] - '0';
i++;
}
}
if (flg == 1){
flg = 0;
if (bjs == 0) {
bjs = js;
js = 0;
}
}
i++;
}
switch (ch) {
case '+':
tmp = bjs + js;
break;
case '-':
tmp = bjs - js;
break;
case '*':
tmp = bjs * js;
break;
default:
bjs = js = 0;
tmp = 0;
break;
}
printf("%d%c%d=%d\n%d\n", bjs, ch, js, tmp, ws(bjs) + ws(js) + ws(tmp) + 2);
}
注意审题,题目说,如果某一行只有两个操作数,默认和上一行的操作一样,但是你默认按照加法做了
输出格式应该是全部输入完然后一起输出吧