#include<iostream>usingnamespace std;
intmain(){
int n;
cin >> n;
int i = 1;
int sum = 0;
while (i <= n) {
if (i % 7 != 0 && i % 10 != 7 && i / 10 != 7) {
sum += (i * i);
}
i++;
}
cout << sum << endl;
return0;
}
2. 多组测试用例
2.1 测试数据组数已知
当题目明确给出测试数据的组数时,可以使用循环结构处理。
示例:多组输入 a+b II
实现示例:
#include<iostream>usingnamespace std;
intmain(){
int n; // 表示数据组数
cin >> n;
int a, b; // 每行输入的 a,b 值while (n--) {
cin >> a >> b;
cout << a + b << endl;
}
return0;
}
示例:斐波那契数列
斐波那契数列特点:前两个数的和是第三个数。有多种解法,如循环嵌套、预计算存储、递归等。
循环嵌套实现示例:
#include<iostream>usingnamespace std;
intmain(){
int n, a;
cin >> n;
while (n--) {
cin >> a;
int x = 1;
int y = 1;
int z = 1;
while (a > 2) {
z = x + y;
x = y;
y = z;
a--;
}
cout << z << endl;
}
return0;
}
#include<iostream>usingnamespace std;
intmain(){
int a, b;
while (cin >> a >> b) {
cout << a + b << endl;
}
return0;
}
原理说明:cin >> a 会返回一个流对象的引用。如果流的状态良好(即没有发生错误),流对象的布尔值为 true;如果发生错误(如遇到输入结束符),布尔值为 false。
示例:定位查找
需要在一个数组中查找特定数字,找到即输出下标并跳出,未找到则输出 No。
实现示例:
#include<iostream>usingnamespace std;
constint N = 25;
int arr[N];
intmain(){
int n, m;
while (cin >> n) {
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cin >> m;
int i = 0;
for (i = 0; i < n; i++) {
if (m == arr[i]) {
cout << i << endl;
break;
}
}
if (i == n) {
cout << "No" << endl;
}
}
return0;
}
#include<iostream>#include<string>usingnamespace std;
intmain(){
string s;
getline(cin, s);
int ret = 0;
for (auto ch : s) {
if (ch >= '0' && ch <= '9') {
ret++;
}
}
cout << ret << endl;
return0;
}
方法二:按照多个单词分析
#include<iostream>#include<string>usingnamespace std;
intmain(){
string s;
int cnt = 0;
while (cin >> s) {
for (auto c : s) {
if (c >= '0' && c <= '9') {
cnt++;
}
}
}
cout << cnt << endl;
return0;
}
2. 数字的特殊处理方式
输入的数字在控制台被视为字符序列,程序会根据变量类型将其解析为整型或字符串。
练习:小乐乐改数字
目标是将奇数位改为 1,偶数位改为 0。
方法一:当做整数读取
利用 % 10 获取末位,判断奇偶,再 / 10 移除末位。
#include<iostream>#include<cmath>usingnamespace std;
intmain(){
int n;
int i = 0, ret = 0;
cin >> n;
while (n) {
if (n % 10 % 2 == 1) {
ret += pow(10, i);
}
n /= 10;
i++;
}
cout << ret << endl;
return0;
}