题目:
用模板类array实现存储一年四个季度的开支
注意:由于模板array不仅可以存储基本的数据类型,还可以存储对象
实现代码:
#include<iostream>
#include<array>
#include<string>
using namespace std;
const int SEASONS = 4;
const array<string, SEASONS> snames = {
"Spring","Summer","Fall","Winter"
};
void fill(array<double, SEASONS>* pa);//由于是修改值,故传入指针进行操作
void show(array<double, SEASONS> da);//显示值,只需要传值即可操作
int main() {
array<double, SEASONS> expenses;
fill(&expenses);//传址
show(expenses);//传值
return 0;
}
void fill(array<double, SEASONS>* pa) {
for (int i = 0; i < SEASONS; ++i) {
cout << "Enter " << snames[i] << " expenses:";
cin >> (*pa)[i];
}
}
void show(array<double, SEASONS> da) {
double total = 0.0;
cout << "\nEXPENSES\n";
for (int i = 0; i < SEASONS; ++i) {
cout << snames[i] << ":$" << da[i] << endl;
total += da[i];
}
cout << "Total Expenses:$" << total << endl;
}
运行结果: