PTA天梯赛练习题 L1-025 正整数A+B


在这里插入图片描述
PTA | 程序设计类实验辅助教学平台

思路简析

  1. 初始拿到这道题的时候其实也没有太多思路,想着定义什么类型好(因为输入的对象是什么还不知道),于是干脆定为string型。
  2. 输入A的时候注意只要到第一个空格之前,所以用 getline(cin, A, ’ ');
  3. 判断一个字符是否为数字用isdigit
  4. stoi可以将字符型转为数字
  5. 利用上述函数可以很好的将题目做出

解法代码

#include<iostream>
#include<cstring>
#include<ctype.h>
using namespace std;
int main() {
    string A, B;
    getline(cin, A, ' ');
    getline(cin, B);
    bool shuA = true;
    bool shuB = true;
    for (int i = 0; i < A.length(); i++) {
        if(!isdigit(A[i])) shuA = false;
    }
    for (int i = 0; i < B.length(); i++) {
        if(!isdigit(B[i])) shuB = false;
    }
    if (shuA) {
        if (stoi(A) > 1000 || stoi(A) < 1) shuA = false;
    }
    if (shuB) {
        if (stoi(B) > 1000 || stoi(B) < 1) shuB = false;
    }
    if (shuA && shuB) {
        cout << stoi(A) << " + " << stoi(B) << " = " << stoi(A) + stoi(B);
    }else if (shuA) {
        cout << stoi(A) << " + " << "?" << " = " << "?";        
    }else if (shuB) {
        cout << "?" << " + " << stoi(B) << " = " << "?";                
    }else {
        cout << "?" << " + " << "?" << " = " << "?";                        
    }
    return 0;
}

相关知识

一些输入的函数C++:cin、cin.getline()、getline()的用法_getline(cin,s)函数用法-优快云博客
判断字符或字符串是否为数字C++中使用isdigit()函数判断字符或字符串是否是数字_c++ isdigit-优快云博客
判断字符书否位数字判断一个字符是否为数字的两种方法(C/C++)_c语言判断是否为数字-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值