首页 > 试题广场 >

修改程序清单8.14,使其使用两个名为SumArray()的

[问答题]
修改程序清单8.14,使其使用两个名为SumArray()的模板函数来返回数组元素的总和,而不是显示数组的内容。程序应显示thing的总和以及所有bebt的总和。
#include <iostream>
using namespace std;

template<typename T>
void showarray(T arr[],int n);

template<typename T>
void showarray(T *arr[],int n);

template <typename T>
T Sumarray (T arr[],int n);

template <typename T>
T Sumarray(T*arr[],int n);

struct debts
{
	char name[50];
	double amount;
};

int main()
{
	int things[6]={13,31,103,301,310,130};
	struct debts mr_E[3]=
	{
		{"Ima wolfe",2400.0},
		{"Ura Foxe",1300.0},
		{"Iby Stout",1800.0}
	};
	double *pd[3];
	for (int i = 0; i < 3; i++)
	{
		pd[i]=&mr_E[i].amount;
	}
	showarray(things,6);
	cout<<"Listing Mr.E's debts"<<endl;
	showarray(pd,3);
	cout<<"The sum of the things:"<<Sumarray(things,6)<<endl;
	cout<<"The sum of pd:"<<Sumarray(pd,3)<<endl;
	system("pause");
	return 0;
}

template<typename T>
void showarray(T arr[],int n)
{
	cout<<"Template A"<<endl;
	for (int i = 0; i < n; i++)
	{
		cout<<arr[i]<<' ';
	}
	cout<<endl;
}
template<typename T>
void showarray(T *arr[],int n)
{
	cout<<"Template B"<<endl;
	for (int i = 0; i < n; i++)
	{
		cout<<*arr[i]<<' ';
	}
	cout<<endl;
}
template <typename T>
T Sumarray (T arr[],int n)
{
	T sum=0;
	for (int i = 0; i < n; i++)
	{
		sum=sum+arr[i];
	}
	return sum;
}
template <typename T>
T Sumarray(T*arr[],int n)
{
	T sum=*arr[0]-*arr[0];
	for (int i = 0; i < n; i++)
	{
		sum=sum+*arr[i];
	}
	return sum;
}

发表于 2021-03-06 20:00:56 回复(0)