定义一组重载函数,分别实现一组int、float、double型数据的相加功能(重载add函数,提示:数组作为函数参数)
时间: 2023-03-28 12:01:42 浏览: 67
好的,这是一个关于函数重载的问题。可以定义一组重载函数,分别实现int、float、double型数据的相加功能。以下是示例代码:
```
#include <iostream>
using namespace std;
int add(int arr[], int n) {
int sum = ;
for (int i = ; i < n; i++) {
sum += arr[i];
}
return sum;
}
float add(float arr[], int n) {
float sum = ;
for (int i = ; i < n; i++) {
sum += arr[i];
}
return sum;
}
double add(double arr[], int n) {
double sum = ;
for (int i = ; i < n; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
float arr2[] = {1.1, 2.2, 3.3, 4.4, 5.5};
double arr3[] = {1.111, 2.222, 3.333, 4.444, 5.555};
cout << "int sum: " << add(arr1, 5) << endl;
cout << "float sum: " << add(arr2, 5) << endl;
cout << "double sum: " << add(arr3, 5) << endl;
return ;
}
```
这个程序定义了三个重载函数,分别用于int、float、double型数据的相加。每个函数都接受一个数组和数组的长度作为参数,并返回数组元素的总和。在主函数中,我们创建了三个不同类型的数组,并分别调用了相应的函数来计算它们的总和。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)