当我在代码中的计算机要求时不输入数组中存在的键时,如何打印"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语句没有执行,意味着没有找到数字,变量的值为假,因此它将打印您询问的行//
#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);
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数