c++ - 程序检查以查看用户编号是否存储在 C++ 中的数组中

标签 c++ arrays user-defined-functions

我写这段代码是为了检查用户输入的正整数是否存储在程序的数组中,然后将结果显示给用户。我是 C++ 的新手,遇到了一些困难。有人可以帮帮我吗。

#include <iostream> //needed for access to cin and cout

using namespace std;

int main (void)
{
    int LS (int [], int);

    int ll=10;
    int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
    int i=0;
    int it=0;
    int result=0;

    cout << " Welcome User, this program allows you to enter a number"<<endl
         << " and see if it is stored in our database."<<endl;

    cout << " Please enter number :  ";
    cin >> it;

    result = LS (l[ll], it); 

    if (result==0)
    {
        cout << " The number" << it << " you entered was not found in our database. " << endl;
    }

    if (result==1)
    {
        cout << " The number" << it << " you entered has been found in our database. " << endl;
    }

    return 0;
} 



int LS (int l[int ll], int it) //function to search for "it"
{

    int i=0, f=0; 

    if (l[i]==it)
    {
        f=1; 
        i++;
    }

    if (i==ll)
    {
        return f;
    }
}

最佳答案

#include <iostream> //needed for access to cin and cout

using namespace std;

int main (void)
{
int LS (int [], int);
int ll=10;
int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
int i=0;
int it=0;
int result=0;

cout << " Welcome User, this program allows you to enter a number"<<endl
  << " and see if it is stored in our database."<<endl;

cout << " Please enter number :  ";
cin >> it;

result = LS (l[ll], it); 
if (result==0){
 cout << " The number" << it << " you entered was not found in our database. " << endl;
}

if (result==1)
{
 cout << " The number" << it << " you entered has been found in our database. " << endl;
}

 return 0;
} 



int LS (int l[int ll], int it) //function to search for "it"{
  int i=0; 
  while (l[i]!=it and i<11){
     i++;
  }
if (i==ll)
   return 0;
return 1;
}

此代码有效,因为如果找到一个元素,则 while 循环将中断,因此 i 值将小于 11

关于c++ - 程序检查以查看用户编号是否存储在 C++ 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25713529/

相关文章:

c++ - 从 C++ 中找到 "~/Library/Application Support"?

c++ - Intel Core i7-3770 上的 ACML 5.3.1 段错误

java - 将字符串转换为 UTF-8 字节数组在 Java 中返回负值

mysql - 将 UDF 从 MS SQL Server 移植到 MySQL 会引发异常,不正确的双值

postgresql - 如何在 IF-THEN-ENDIF 条件下使用存储过程返回 bool 值?

c++ - 使用 constexpr 而不仅仅是静态 const 变量还能提供什么?

c代码使用递归打印数组的反向

c++ - 如果在 C++ 中创建 arr 的函数外部调用,delete [] arr 是否会释放内存?

javascript - 如何使用用户定义的过滤器或其他方法控制通过 CSS 模块或样式化组件自动生成的动态类名

c++ - 混合 C 和 C++、原始指针和( boost )共享指针