入门题目
2026-07-31 20:27:26
发布于:江苏
11阅读
0回复
0点赞
这题需要仔细读题,题目中说跳过第一个和m相等的数。
我们先输入:
int a[1005];//定义数组
//…… …… …… …… …… ……
ios::sync_with_stdio(false);
cin.tie(nullptr);//加快输入速度
int n;//定义n
cin >> n;//输入个数
for(int i = 1; i <= n; i++) cin >> a[i];//输入各数
下面👇是重点,先看错误❌️代码:
1.
int m;
cin >> m;
for(int i = 1; i <= n; i++) if(a[i] != m) cout << a[i] << ' ';
看似是跳过了数m,但题目中只让我们跳过第一个。所以是错的❌️。
2.
int m;
cin >> m;
for(int i = 1; i <= n; i++){
if(a[i] == m){
a[i] = 0;
break;
}
for(int i = 1; i <= n; i++) if(a[i] != 0) cout << a[i] << ' ';
但这又又又又又踩坑了,题目中数据范围刚好允许0。哎😔。
好了,现在该说正确思路了,我是这样做的,先定义一个布尔类型的变量,初始为真。遇到m的时候,如果是真,那么把变量调成假不输出;否则正常输出
这个部分的正确代码:
int k;
cin >> k;
bool f = true;//哪个布尔类型的变量
for(int i = 1; i <= n; i++){
if(f && a[i] == k) f = false; //调整变量
else cout << a[i] << ' ';
}
全部代码(总结)(不加注释了……):
#include<iostream>
using namespace std;
int a[1005];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
int k;
cin >> k;
bool f = true;
for(int i = 1; i <= n; i++){
if(f && a[i] == k) f = false;
else cout << a[i] << ' ';
}
return 0;
}
这里空空如也







有帮助,赞一个