C++-练习-60

 题目:

修改以下程序,使其使用两个名为SumArray()的模板函数来返回数组元素的总和,而不是显示数组的内容。程序应显示thing的总和以及所有debt的总和

#include <iostream>

template <typename T>

void ShowArray(T arr[], int n);

template <typename T>

void ShowArray(T* arr[], int n);

struct debts

{

char name[50];

double amount;

};

int main()

{

using namespace std;

int things[6] = { 13,31,103,301,310,130 };

struct debts mr_E[3] =

{

{"Tma 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;

}

cout << "Listing Mr.E's counts of things:\n";

ShowArray(things, 6);

cout << "Listing Mr.E's debts:\n";

ShowArray(pd, 3);

return 0;

}

template <typename T>

void ShowArray(T arr[], int n)

{

using namespace std;

cout << "template A\n";

for (int i = 0; i < n; i++)

cout << arr[i] << ' ';

cout << endl;

}

template <typename T>

void ShowArray(T* arr[], int n)

{

using namespace std;

cout << "template B\n";

for (int i = 0; i < n; i++)

cout << *arr[i] << ' ';

cout << endl;

}

源代码:

#include <iostream>

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

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

template <>float SumArray(debts arr[], int n);



int main()
{
	using namespace std;
	int things[6] = { 13,31,103,301,310,130 };

	struct debts mr_E[3] =
	{
		{"Tma Wolfe",2400.2},
		{"Ura Foxe",1300.3},
		{"Iby Stout",1800.0}
	};


	cout << "things 总和: " << SumArray(things, 6) << endl;
	cout << "debt总和: " << SumArray(mr_E, 3);
	return 0;
}

template <typename T>
float SumArray(T arr[], int n)
{
	int total = 0;
	for (int i = 0; i < n; i++)
	{
		total = total + arr[i];
	}
	return total;
}

template <> float SumArray(debts arr[], int n)
{
	double total = 0;
	for (int i = 0; i < n; i++)
	{
		total = total + arr[i].amount;
	}
	return total;
}

演示效果:

75dfb0be65798b47659333621cd28635.png


如果朋友你感觉文章的内容对你有帮助,可以点赞关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈

猜你喜欢

转载自blog.csdn.net/little_startoo/article/details/143279527