#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int usman[10]={0,5,6,3,5,1,8,5,4};
int choice;
cout<<"Please Neter A Value To search : ";
cin>>choice;
cout<<endl;
for( int j=0 ; j<10 ; j++)
{
if(usman[j]==choice)
{
cout<<"usman["<<j<<"] = "<<choice<<endl;
}
}
getch();
return 0;
}
先生,
这个程序没有错误。在这个程序中我创建了一个 Var 数组。这是 Initialized 。在屏幕上,它要求用户搜索数组中的任何数字并告诉 n 它存在哪些索引。我想添加一件事,如果用户给定的数字不在数组列表中,它会简单地显示一个消息。 “给定的数字不存在”只有一次,而不是多次。我的意思是,当用户的选择不在第一个数组中时,在循环的每个轮换中等等,它不会每次都显示消息。
谢谢。
最佳答案
添加一个额外的 bool 变量来检查是否找到了数字。如果多次找到,多次应用 found = true
与只应用一次相同。
bool found = false;
for( int j=0 ; j<10 ; j++)
{
if(usman[j]==choice)
{
cout<<"usman["<<j<<"] = "<<choice<<endl;
found = true;
}
}
if (!found)
{
cout << "The given number does not exist!" << endl;
}
关于c++ - 从数组列表中用户搜索一个数字,如果没有找到,则只显示一个未找到的消息,而不是多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20189459/