练习 P1957 口算练习题

题目来源:洛谷
题意:输入多行数据,每行有三个(一个字母两个非负整数,形如:a 1 2)或两个数据(两个非负整数,形如:1 2)。将其以算式的形式表示,并给出算式的总长度,a代表加法,b代表减法, c代表乘法,只有两个数据时,运算类型与上一行数据相同。
样例
输入:
4
a 64 46
275 125
输出:
64+46=110
9
275+125=400
11

  • 个人感觉不好处理的主要是不确定一行有几个数据。看了很多题解感觉下面处理这一点的思路还算可以的吧。其他的都在注释里了。
#include<bits/stdc++.h>
using namespace std;

int StrToInt(string str)//字符串转数字
{
    int numb = 0;
    for(int i=0; i<str.length(); i++)
    {
        numb = numb * 10 + (str[i] - '0');
    }
    return numb;
}
int NumOfNum(int n, int allsum)//计算某整数的位数
{
    if(n == 0) allsum++; //当该整数为0,只有下面的while就不能返回正确位数了
    while(n > 0)
    {
        n /= 10;
        allsum++;
    }
    return allsum;
}
void solve(char ch, int a, int b) //运算过程+算式总长度计算+输出
{
    int allsum = 2, sum = 0;
    if(ch == 'a')
    {
        sum = a + b;
        cout << a << "+" << b << "=" << sum << endl;
    }
    else if(ch == 'b')
    {
        sum = a - b;
        cout << a << "-" << b << "=" << sum << endl;
    }
    else if(ch == 'c')
    {
        sum = a * b;
        cout << a << "*" << b << "=" << sum << endl;
    }
    if(sum < 0)
    {
        allsum++;
        sum = sum * -1;
    }
    allsum = NumOfNum(a, allsum);
    allsum = NumOfNum(b, allsum);
    allsum = NumOfNum(sum, allsum);
    cout << allsum << endl;
}
int main()
{
    int cou, ans = 0, a, b;
    string str1, str2 , str3;
    cin >> cou;
    char ch[100];

    while(ans < cou)
    {
        ans++;
        cin >> str1 >> str2;
        //数据获取
        if(str1 != "a" && str1 != "b" && str1 != "c")
        {//str1不是字母,说明这一行只有两个数据
            a = StrToInt(str1);
            b = StrToInt(str2);
            //回溯上一个存在的运算符,注意不要改变ans本身的值
            int anss = ans;
            while(ch[anss] != 'a' && ch[anss] != 'b' && ch[anss] != 'c')
            {
                anss--;
            }
            solve(ch[anss], a, b);
        }
        else
        {//这一行存在三个数据,需要再获取一次
            cin >> str3;
            ch[ans] = str1[0];
            a = StrToInt(str2);
            b = StrToInt(str3);
            solve(ch[ans], a, b);
        }
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值