在 c++ 中循环遍历数组时遇到问题

Having trouble looping through an array in c++

本文关键字:遇到 问题 数组 遍历 c++ 循环      更新时间:2023-10-16

我似乎错误地循环了我的数组,我已经将其设置为提示用户输入数字列表,并且我应该将其与用户设置的另一个数字进行比较。

#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}

我假设以下代码是问题所在。这个想法是我设置 s = 2 输入数字列表,然后与 s 进行比较并打印 s,如果有匹配项,如果没有,我打印未找到匹配项。当我输入一个我知道匹配的数字时,它似乎打印了数组中的第一个数字,但我认为既然我在 for 循环中逐个循环数字,它应该在到达正确的数字时显示,而不是在它停止时显示。提前致谢

//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}

您使用的是单个等号。这会将s设置为userArray[i],因此它始终计算为 true。为了进行比较,请使用双等号,如下所示:
if (s == userArray[i]) {...}
此外,您的return语句在您的循环内(归功于@UnholySheep(。

您正在与单个赋值运算符进行比较=您应该使用相等运算符而不是==

if (s = userArray[i])in for 循环就是一个例子。

你也犯了同样的错误

if (chk = true)