我正在尝试在数组中搜索值。阵列是否需要一个确定的数字?我该如何搜索这个号码?谢谢你的帮助!
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "windows.h"
using namespace std;
int main() {
int userinput;
int arrayofnumber[10] = { 5, 3, 77, 43, 6, 22, 7, 9, 84, 26 };
int NumberInArray = sizeof(arrayofnumber) / sizeof(arrayofnumber[0]);
cout << "What Number Would You Like To Search For? \n";
cout << "Number of Values in Array = " << NumberInArray << endl;
cin >> userinput;
for (int i = 0; i >= NumberInArray; i++) {
if (userinput == NumberInArray[i]) {
cout << "We Found IT! It = " << NumberInArray[i] << endl;
}
}
return 0;
}
答案 0 :(得分:2)
for (int i = 0; i < NumberInArray; i++) {
if (userinput == arrayofnumber[i]) {
cout << "We Found IT! It = " << arrayofnumber[i] << endl;
break;
}
}
您的for
循环条件i >= NumberInArray
错误。它应该是i < NumberInArray
。
NumberInArray[i]
是非法的。你应该arrayofnumber[i]
。
添加了break
,以便在找到号码时,您可以退出循环。
答案 1 :(得分:1)
该标准为我们提供find
来执行此操作。所以我建议使用C ++的实现而不是自己编写它,这样做也会消除你对NumberInArray
的需求:
if(cend(arrayofnumber) != find(cbegin(arrayofnumber), cend(arrayofnumber), userinput)) cout << "We Found IT! It = " << userinput << endl;