【发布时间】:2018-10-04 20:40:20
【问题描述】:
我似乎在循环我的数组时出错了,我已经将它设置为提示用户输入数字列表,并且我应该将它与用户设置的另一个数字进行比较。
#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 我打印没有找到匹配项。当我输入一个我知道与 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!";
}
【问题讨论】:
-
检查您的
return 0;的放置位置。i <= 10也应该是i < 10 -
尝试使用最高的编译器警告,然后编译器会指出错误。
标签: c++ arrays visual-c++