码迷,mamicode.com
首页 > 其他好文 > 详细

自考新教材-p352_3(2)

时间:2020-02-06 10:55:04      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:std   nbsp   面向   fine   ima   for   using   图片   com   

源程序:用面向对象方法又做一遍

#include <iostream>
#define N 10
using namespace std;

template <typename T>

class sum_array
{
private:
T a[N];
public:
sum_array(T a1[])
{
for (int i = 0; i < N; i++)
a[i] = a1[i];
}
T cal_sum(T a[], int n)
{
int i, size;
T sum = 0;
cout << "您想求数组前几项的和,请输入:";
cin >> size;
for (i = 0; i < size; i++)
{
sum = sum + a[i];
}
return sum;
}
};


int main()
{

int num[N] = {1,3,5,7,9,2,4,6,8,0};
sum_array <int>suma(num);
int result = suma.cal_sum(num,N);
cout << result << endl;

cout << endl;


double num1[N] = { 1.1,3.3,5.5,7.7,9.9,2.2,4.4,6.6,8.8,0.0 };
sum_array <double>suma1(num1);
double result1 = suma1.cal_sum(num1, N);
cout << result1 << endl;

cout << endl;
/*
char num2[N] = { ‘a‘,‘c‘,‘e‘,‘f‘,‘h‘,‘m‘,‘p‘,‘b‘,‘j‘,‘d‘ };
int result2 = sum_array(num2, N);
cout << result2 << endl;
*/
system("pause");
return 1;
}

运行结果:

技术图片

 

自考新教材-p352_3(2)

标签:std   nbsp   面向   fine   ima   for   using   图片   com   

原文地址:https://www.cnblogs.com/duanqibo/p/12267733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!