两种方法编写程序,创建一个4行4列的一维数组,按下图要求存储数据,并输 出。考虑整型、小数等不同类型的数组。 方法1函数原型:void sun(int a[], int size=16); void sum(double a(], int size=16): 方法2函数模板原型: template<typename T> void sum(T all, int size=16);
时间: 2024-03-25 19:41:51 浏览: 76
方法1:
```cpp
#include <iostream>
using namespace std;
void sum(int a[], int size = 16);
void sum(double a[], int size = 16);
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
double b[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.2, 12.3, 13.4, 14.5, 15.6, 16.7};
sum(a);
sum(b);
return 0;
}
void sum(int a[], int size) {
cout << "int array: " << endl;
for (int i = 0; i < size; i++) {
if (i % 4 == 0) {
cout << endl;
}
cout << a[i] << " ";
}
cout << endl;
}
void sum(double a[], int size) {
cout << "double array: " << endl;
for (int i = 0; i < size; i++) {
if (i % 4 == 0) {
cout << endl;
}
cout << a[i] << " ";
}
cout << endl;
}
```
方法2:
```cpp
#include <iostream>
using namespace std;
template<typename T>
void sum(T all, int size = 16);
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
double b[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.2, 12.3, 13.4, 14.5, 15.6, 16.7};
sum(a);
sum(b);
return 0;
}
template<typename T>
void sum(T all, int size) {
cout << typeid(all).name() << " array: " << endl;
for (int i = 0; i < size; i++) {
if (i % 4 == 0) {
cout << endl;
}
cout << all[i] << " ";
}
cout << endl;
}
```
注意,方法2使用了函数模板,可以对不同类型的数组进行处理,但是需要注意的是,在调用 `typeid` 函数时,需要包含 `<typeinfo>` 头文件。
阅读全文