当计算机在我的代码中要求时,当我没有输入数组中存在的键时如何打印 "The key(element) is not present in your array"
How to print "The key(element) is not present in your array" when I don't enter a key present in my array when asked for by the computer in my code
假设我输入 {1,3,3,5}
作为我的数组,当要求输入我想知道其索引的键时,我输入 6。如何编辑我的代码以打印“输入的键不在您的数组中”?
我的代码如下:
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
}
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}
// 你可以在 void 函数中使用一个布尔控制变量,当你找到数字时,你可以将它的值设置为 true 并在循环结束时插入一个 if 语句来检查 bool 变量的值,如果没有执行循环中的 if 语句,则意味着未找到数字并且变量的值为 false,因此它将打印您询问的行 //
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
bool found = false;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
found = true;
}
}
if (found == false){
cout << "The key entered is not in your array." << endl;
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}
假设我输入 {1,3,3,5}
作为我的数组,当要求输入我想知道其索引的键时,我输入 6。如何编辑我的代码以打印“输入的键不在您的数组中”?
我的代码如下:
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
}
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}
// 你可以在 void 函数中使用一个布尔控制变量,当你找到数字时,你可以将它的值设置为 true 并在循环结束时插入一个 if 语句来检查 bool 变量的值,如果没有执行循环中的 if 语句,则意味着未找到数字并且变量的值为 false,因此它将打印您询问的行 //
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
bool found = false;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
found = true;
}
}
if (found == false){
cout << "The key entered is not in your array." << endl;
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}