L1-025. 正整数A+B

    xiaoxiao2021-03-25  143

    本题要求:

    本题的目标很简单,就是求两个正整数A和B的和,其中A和B都在区间[1,1000]。稍微有点麻烦的是,输入并不保证是两个正整数。

    输入格式:

    输入在一行给出A和B,其间以空格分开。问题是A和B不一定是满足要求的正整数,有时候可能是超出范围的数字、负数、带小数点的实数、甚至是一堆乱码。 注意:我们把输入中出现的第1个空格认为是A和B的分隔。题目保证至少存在一个空格,并且B不是一个空字符串。

    输出格式:

    如果输入的确是两个正整数,则按格式“A + B = 和”输出。如果某个输入不合要求,则在相应位置输出“?”,显然此时和也是“?”。

    输入样例:

    123 456

    输出样例:

    123 + 456 = 579

    解题思路 :

    注意读取第二次字符串时,需要读取整行,并且读取整行时,缓冲区还多出来一个空格,只需将空格设置为0即可。

    代码 :

    #include<iostream> #include<cstring> using namespace std; int toInt(char *str) { int n = 0; int m = 1; int size = strlen(str); for (int i = size - 1; i >= 0; i--) { if (str[i] < '0' || str[i] > '9') { return 0; } n += (str[i] - '0') * m; m *= 10; } if (n > 1000) { return 0; } return n; } int main() { char str1[1001],str2[1001]; cin >> str1; cin.getline(str2,1009); str2[0] = '0'; int n = toInt(str1); int m = toInt(str2); if (n == 0) { cout << "?"; } else { cout << n; } cout << " + "; if (m == 0) { cout << "?"; } else { cout << m; } cout << " = "; if (n == 0 || m == 0) { cout << "?"; } else { cout << n + m; } cout << endl; return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-5707.html

    最新回复(0)