P1957 口算练习题

在这里插入图片描述
在这里插入图片描述
这个题的难点在于每行输入的变量数量不定。
参考了题解之后,我的写法是这样的:在这里插入图片描述
输入的第一个变量定为char,相当于只读一位,后面两个变量为string,判断char不是a或b或c时,利用字符串的性质,把char连接到string前面。

还有一点要注意的是,在计算字符串长度的时候,也要计算’-'的长度(即特殊判断负数),而且0的长度为1而不是0。

然后看一下完整代码:

#include<bits/stdc++.h>
using namespace std;
int length(int num)
{
	int t=0;
	if(num==0||num<=0)t++;
	while(num)//而不是num>=0
	{
		t++;
		num/=10;
	}
	return t;
}
int change(string s)
{
	int sum=0;
	for(int i=0;i<s.size();i++)
	{
		sum=sum*10+s[i]-48;
	}
	return sum;
}
int main()
{
	int n,oper;
	char ch;
	string sa,sb;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>ch>>sa>>sb;
		if(ch=='a')oper=1;
		else if(ch=='b')oper=2;
		else if(ch=='c')oper=3;
		else if(ch>='0'&&ch<='9')sa=ch+sa;//字符串的连接
		int a=change(sa),b=change(sb);
		int lena=length(a),lenb=length(b);
		if(oper==1)printf("%d+%d=%d\n%d\n",a,b,a+b,lena+lenb+2+length(a+b));
		else if(oper==2)printf("%d-%d=%d\n%d\n",a,b,a-b,lena+lenb+2+length(a-b));
		else if(oper==3)printf("%d*%d=%d\n%d\n",a,b,a*b,lena+lenb+2+length(a*b));
	}
}
//int main()
//{
//	int n;
//	string oper[60];
//	int n1[60],n2[60],ans[60];
//	cin>>n;
//	for(int i=1;i<=n;i++)
//	{
//		cin>>oper[i];
//		if(oper[i]=="a"||oper[i]=="b"||oper[i]=="c")
//		{
//			cin>>n1[i]>>n2[i];
//			if(oper[i]=="a")
//			{
//				oper[i]="+";
//				ans[i]=n1[i]+n2[i];
//			}
//			else if(oper[i]=="b")
//			{
//				oper[i]="-";
//				ans[i]=n1[i]-n2[i];
//			}
//			else if(oper[i]=="c")
//			{
//				oper[i]="*";
//				ans[i]=n1[i]*n2[i];
//			}
//		}
//		else
//		{
//			n1[i]=int(oper[i]);
//			cin>>n2[i];
//			oper[i]=oper[i-1];
//			if(oper[i]=="a"||oper[i]=="+")
//			{
//				oper[i]="+";
//				ans[i]=n1[i]+n2[i];
//			}
//			else if(oper[i]=="b"||oper[i]=="-")
//			{
//				oper[i]="-";
//				ans[i]=n1[i]-n2[i];
//			}
//			else if(oper[i]=="c"||oper[i]=="*")
//			{
//				oper[i]="*";
//				ans[i]=n1[i]*n2[i];
//			}
//		}
//	}
//	for(int i=1;i<=n;i++)
//	{
//		cout<<n1[i]<<char(oper[i])<<n2[i]<<"="<<ans[i]<<endl;
//		cout<<(length(n1[i])+length(n2[i])+length(ans[i])+2)<<endl;
//	}
//}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值