在 c++ 中循环遍历数组时遇到问题
Having trouble looping through an array in c++
我似乎错误地循环了我的数组,我已经将其设置为提示用户输入数字列表,并且我应该将其与用户设置的另一个数字进行比较。
#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)
相关文章:
- 编译包含字符串的代码时遇到问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题
- 存储另一个函数返回的布尔数组时遇到问题
- 我在 OpenGL 中显示图像时遇到问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 在 for 循环中更新两个变量时遇到问题C++
- 为什么我的程序在打开网络设备时遇到问题
- 在 Tensorflow C++ 中使用 FIFOQueue 时遇到问题
- 为什么我在虚幻引擎中的多态性和接口方面遇到问题?