E02676: 整数的个数
math, http://cs101.openjudge.cn/pctbook/E02676/
给定k(1< k < 100)个正整数,其中每个数都是大于等于1,小于等于10的数。写程序计算给定的k个正整数中,1,5和10出现的次数。
输入
输入有两行:第一行包含一个正整数k,第二行包含k个正整数,每两个正整数用一个空格分开。
输出
输出有三行,第一行为1出现的次数,,第二行为5出现的次数,第三行为10出现的次数。
样例输入
5
1 5 8 10 5样例输出
1
2
1来源
计算概论05-模拟考试1
cpp
#include <iostream>
using namespace std;
int main() {
int k;
cin >> k;
int cnt1 = 0, cnt5 = 0, cnt10 = 0;
for (int i = 0; i < k; i++) {
int x;
cin >> x;
if (x == 1) cnt1++;
else if (x == 5) cnt5++;
else if (x == 10) cnt10++;
}
cout << cnt1 << endl;
cout << cnt5 << endl;
cout << cnt10 << endl;
return 0;
}cpp
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int k;
cin >> k;
cin.ignore(); // 忽略掉换行符
string line;
getline(cin, line); // 读入整行数字
stringstream ss(line);
int x, cnt1 = 0, cnt5 = 0, cnt10 = 0;
while (ss >> x) { // 按空格自动分割。>> 操作符自动忽略多余的空格、换行符
if (x == 1) cnt1++;
else if (x == 5) cnt5++;
else if (x == 10) cnt10++;
}
cout << cnt1 << "\n" << cnt5 << "\n" << cnt10 << endl;
return 0;
}【鲍雷栋,2021年秋,物理学院】
由于 Python 对整型高精度的支持,对 C++ 及其他语言使用者来说学习 Python 基础语法是有必要的。应当说,学习 Python 中的一道坎是接受它的输入和输出方式,在习惯了其他语言输入输出方式后再学 Python 的直接一行输入一行输出的方式有种“难以理解”的感觉,仿佛无形之中增添了麻烦。
但在一些输入形式上,Python 自带的函数却提供了便捷,例如split。为了让 C++ 选手们减少不必要的痛苦,将 C++ 中实现 split 的代码放在下面,实现利用了 stringstream 和 vector,如果需要读取 int 或 double,利用自带的 stoi 或 stod 转换即可。
cpp
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
// 模拟 Python 的 split 函数
vector<string> split(string str, char sp) {
istringstream iss(str);
vector<string> res;
string subs;
while (getline(iss, subs, sp)) {
if (!subs.empty()) res.push_back(subs);
}
return res;
}
int main() {
int k;
cin >> k; // 读入 k
cin.ignore(); // 忽略掉换行符,不然 getline 会读到空行
string line;
getline(cin, line); // 一次性读入整行数字
vector<string> nums = split(line, ' '); // 按空格分割
int cnt1 = 0, cnt5 = 0, cnt10 = 0;
for (string s : nums) {
int x = stoi(s); // 转换为整数
if (x == 1) cnt1++;
else if (x == 5) cnt5++;
else if (x == 10) cnt10++;
}
cout << cnt1 << "\n" << cnt5 << "\n" << cnt10 << endl;
return 0;
}