8.在不使用 array 类的情况下完成程序清单 7.15 所做的工作。编写两个这样的版本:
a.使用const char* 数组存储表示季度名称的字符串,并使用double 数组存储开支。
b.使用const char*数组存储表示季度名称的字符串,并使用一个结构,该结构只有一个成员------ -个用于存储开支的 double 数组。
这种设计与使用 array 类的基本设计类似。
做此题之前,我们的先把7.15的程序复习一下,看下改程序如何实现的。
下面是主函数,主函数中调用了fill(),show()函数
//arrobj.cpp -- functions with array objects
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const std::array<std::string, Seasons> Snames =
{"Spring", "Summer", "Fall", "Winter"};
void fill(std::array<double, Seasons> * pa);
void show(std::array<double, Seasons> da);
int main()
{
std::array<double, 4> expenses;
fill(&expenses);
show(expenses);
// std::cin.get();
// std::cin.get();
return 0;
}
fill函数的实现。fill实现对数组的填充,参数是定义的array数组指针
void fill(std::array<double, Seasons> * pa)
{
for (int i = 0; i < Seasons; i++)
{
std::cout << "Enter " << Snames[i] << " expenses: ";
std::cin >> (*pa)[i];
}
}
show 函数是对数组的显示输出
void show(std::array<double, Seasons> da)
{
double total = 0.0;
std::cout << "\nEXPENSES\n";
for (int i = 0; i < Seasons; i++)
{
std::cout << Snames[i] << ": $" << da[i] << '\n';
total += da[i];
}
std::cout << "Total: $" << total << '\n';
}
函数看完了。本次的主要任务在对fill(),和show的改造,
先看第一个问题
a.使用const char* 数组存储表示季度名称的字符串,并使用double 数组存储开支。
函数的声明
void fill(double* );
void show(double[]);
下面来实现void fill(double*)
函数对指针指向的数组进行填充,这里说指针或者数组
void fill(double* pa)
{
using namespace std;
for (int i = 0; i < Seasons; i++)
{
cout << "请输入 " << Snames[i] << " 的费用: ";
cin >> pa[i];
}
}
void show(double []);显示和求和
void show(double da[])
{
using namespace std;
double total = 0.0;
cout << "\n支出费用\n";
for (int i = 0; i < Seasons; i++)
{
cout << Snames[i] << ": $" << da[i] << endl;
total += da[i];
}
cout << "总共支出费用: $" << total << endl;
}
下面main的代码贴上来,主函数没啥内容
const int Seasons = 4;
const char* Snames[] = { "春", "夏", "秋", "冬" };
int main()
{
double expenses[Seasons];
fill(expenses);
show(expenses);
return 0;
}
}
b.使用const char*数组存储表示季度名称的字符串,并使用一个结构,该结构只有一个成员------ -个用于存储开支的 double 数组。
这种设计与使用 array 类的基本设计类似。
b.这种情况用封装结构体的方式,实现
这里我把结构体和函数声明给出来,具体实现看通宵们的
struct Data
{
doublt arr[MAX];
}Data_t,d;
void fill(Data*)
void show(Data)
下面给出整体的代码方便兄弟们学习
#pragma region 8.cpp 7.8a
/*
8.在不使用 array 类的情况下完成程序清单 7.15 所做的工作。编写两个这样的版本:
a.使用const char* 数组存储表示季度名称的字符串,并使用double 数组存储开支。
b.使用const char* 数组存储表示季度名称的字符串,并使用一个结构,该结构只有一个成员------ - 个用于存储开支的 double 数组。
*/
#if 1
#include <iostream>
#include <string>
// constant data
const int Seasons = 4;
const char* Snames[] = { "第一季度", "第二季度", "第三季度", "第四季度" };
void fill(double* pa)
{
using namespace std;
for (int i = 0; i < Seasons; i++)
{
cout << "请输入 " << Snames[i] << " 的费用: ";
cin >> pa[i];
}
}
void show(double da[])
{
using namespace std;
double total = 0.0;
cout << "\n支出费用\n";
for (int i = 0; i < Seasons; i++)
{
cout << Snames[i] << ": $" << da[i] << endl;
total += da[i];
}
cout << "总共支出费用: $" << total << endl;
}
int main()
{
double expenses[Seasons];
fill(expenses);
show(expenses);
return 0;
}
#endif
#pragma endregion