洛谷P1957 口算练习题

P1957 口算练习题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

我自己的代码 比较长

#include <iostream>
#include <cstring>
using namespace std;
int wei(int u)//统计一个数的位数 
{
	int idx = 0;
	if (u < 0) idx++,u = -u;
	if (u == 0) return 1;
	while(u)
	{
		u /= 10;
		idx++;
	}
	return idx;
}

void op(char a2, int b2, int c2)
{
	if (a2 == 'a') 
		{
			cout << b2 << "+" << c2 << "=" << b2+c2 << endl;
			cout << wei(b2) + wei(c2) + wei(b2+c2) + 2 << endl;
		}
		else if (a2 == 'b')
		{
			cout << b2 << "-" << c2 << "=" << b2-c2 << endl;
			cout << wei(b2) + wei(c2) + wei(b2-c2) + 2 << endl;
		}
		else if (a2 == 'c')
		{	
			cout << b2 << "*" << c2 << "=" << b2 * c2 << endl;
			cout << wei(b2) + wei(c2) + wei(b2*c2) + 2 << endl;
		}
	return;
}


int main()
{
	int i, b1, c1;
	scanf("%d", &i);
	while (i--)
	{
		char a[10000], b[10000], c[10000],t;
		cin >> a;
		if (a[0] >= 'a' && a[0] <= 'c') 
		{
			t = a[0];
			cin >> b >> c;
			sscanf(b, "%d", &b1);//把数字字符串b转化成int b1 
			sscanf(c, "%d", &c1);
			op(t, b1, c1);
		}
		else
		{
			strcpy(b, a);//把字符串a复制给b 
			cin >> c;
			sscanf(b, "%d", &b1);
			sscanf(c, "%d", &c1);
			op(t, b1, c1);//如果这一行没有操作 t保存的是上一次操作 
		} 	
	}
	return 0;
}

先介绍以下sscanf和sprintf

char str[100];
sscanf(str,"%d",&n);//将str转换为"%d"的n
sprintf(str,"%d",n);//将"%d"的n转换为str

洛谷大佬题解的思路和代码

#include <iostream> 
#include <cstring> //memset & strlen 用cstring
#include <cstdio> //sscanf & sprintf 用cstdio
using namespace std;
int main()
{
	char a;//a用于存储运算符
	int n, c, d;
	char s[100], b[10];//s存储最终的字符串,b临时变量
	
	cin >> n;
	
	for(int i = 0; i < n; i++)
	{
		cin >> b;//输入一串字符,有可能是运算符,也有可能是数字
		
		if(b[0] >= 'a' && b[0] <= 'z')
		{
			a = b[0];//如果是运算符就存入a,然后输入数字
			cin >> c >> d;
		}
		else
		{
			sscanf(b, "%d", &c);//如果是数字就转换b为int存储到第一个数字
			cin >> d;//然后输入剩下的第二个数字
		}
		memset(s, 0, sizeof(s) );//清空原有的字符串,防止长度判断错误
		
		if(a == 'a') sprintf(s, "%d+%d=%d", c, d, c+d);//用sprintf格式化
		else if(a=='b') sprintf(s, "%d-%d=%d", c, d, c-d);
		else if(a=='c') sprintf(s, "%d*%d=%d", c, d, c*d);
		
		cout << s << endl << strlen(s) << endl;//输出字符串和字符串长度
	}
	return 0;
}

字符串操作繁琐 

要加强相关语法!!!

多记strcpy,sscanf,sprintf之类的函数

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值