TB椰程 TypeBuddy 打字搭子

口算练习题

洛谷·深入浅出 · 代码 · cpp · 难度 3/5 · 共 1036 字

按算式类型输出完整等式及其总长度

  • 洛谷
  • 例题

正文

// 原题:https://oj.yecheng.tv/p/1417
// 题意:第一行 i 表示 i 道算式。之后每行可能是「类型 a/b/c 两个运算数」或「两个运算数」(沿用上一题类型)。
//       对每题输出完整算式与结果,第二行输出算式总长度。
// 思路:用字符变量记录上一题类型;a 加、b 减、c 乘,拼成等式字符串,长度即字符串 size()。
// 复杂度:O(i)。
// 易错点:长度包含数字、运算符和等号;连续两数据行要沿用上面记录的类型。
#include <iostream>
#include <string>
using namespace std;
int main(){
    int i;
    cin >> i;
    char type = 'a';
    for(int k = 0; k < i; k++){
        string t;
        cin >> t;
        int x, y;
        if(t == "a" || t == "b" || t == "c"){
            type = t[0];
            cin >> x >> y;
        } else {
            x = stoi(t);
            cin >> y;
        }
        string expr;
        int res;
        if(type == 'a'){ res = x + y; expr = to_string(x) + "+" + to_string(y) + "=" + to_string(res); }
        else if(type == 'b'){ res = x - y; expr = to_string(x) + "-" + to_string(y) + "=" + to_string(res); }
        else { res = x * y; expr = to_string(x) + "*" + to_string(y) + "=" + to_string(res); }
        cout << expr << endl << expr.size() << endl;
    }
    return 0;
}

洛谷·深入浅出的其它内容

打字首页 · 词库画廊 · 编程打字 · 指法入门 · 天梯榜 · 数据分析 · 班级课堂 · 关于我们
椰程 TypeBuddy 打字搭子 —— 键盘指法练习 · 单词记忆 · 班级课堂 · 在线 PK