【问题描述】函数重载:数据查找

【问题描述】函数重载:数据查找

编写重载函数Finddata,查找整型数组和字符数组中的特定数据,找到函数返回第一个数据的下标,找不到返回-1。设main函数中的部分代码如下,请根据输入、输出格式,完成程序。

int main()

{

int fid, arr[] = {-11,3,5,13,27,8,23,45,2,3,-14,0,43,20,2,30,5,45,0,42,38,67 };

char ch,str[] = "The university seeks to integrate social service into its schooling.";

int N = sizeof(arr) / sizeof(int);

cin>>fid;//fid为要查找的整数

int i = Finddata(arr, N, fid);

…………………………………………………………………………//省略若干条语句

cin>>ch; //ch为要查找的字符

i = Finddata(str, ch);

…………………………………………………………………………//省略若干条语句

return 0;

}

【输入输出形式】

27 (用户输入要查找的整数27)

Found:4 (程序输出查找到的整数27的下标4)

u (用户输入要查找的字符u)

Found:4 (程序输出查找到的字符u的下标4)

【样例输入输出】

20

Found:13

X

Not Found!

【样例说明】

arr及str数组为系统样例测试数据,不得修改。

【评分标准】

你题目的解答代码如下:

#include <iostream>
using namespace std;
int Finddata(int arr[],int N,int fid)
{
    for (int i = 0; i < N; i++)
        if (arr[i]==fid)
            return i;
    return -1;
}
int Finddata(char str[],char ch)
{
    for (int i = 0; str[i]!='\0'; i++)
        if (str[i]==ch)
            return i;
    return -1;
}
int main()
{
    int fid, arr[] = {-11, 3, 5, 13, 27, 8, 23, 45, 2, 3, -14, 0, 43, 20, 2, 30, 5, 45, 0, 42, 38, 67};
    char ch, str[] = "The university seeks to integrate social service into its schooling.";
    int N = sizeof(arr) / sizeof(int);
    cin >> fid; //fid为要查找的整数
    int i = Finddata(arr, N, fid);
    if (i != -1)
        cout << "Found:" << i << endl;
    else
        cout << "Not Found!" << endl;
    cin >> ch; //ch为要查找的字符
    i = Finddata(str, ch);
    if (i != -1)
        cout << "Found:" << i << endl;
    else
        cout << "Not Found!" << endl;
    return 0;
}

如有帮助,望采纳!谢谢!