【C++ Primer Plus习题】10.4

问题:

解答:

main.cpp

cpp 复制代码
#include <iostream>
#include "sales.h"
using namespace std;
using namespace SALES;

int main()
{
	Sales s1;
	double de[QUARTERS] = { 12.1,32.1,42.1,51.1 };
	Sales s2(de, QUARTERS);
	
	s1.showSales();
	s2.showSales();

	return 0;
}

sales.h

cpp 复制代码
#pragma once

namespace SALES
{
	const int QUARTERS = 4;
	class Sales
	{
	public:
		Sales();
		Sales(double ar[], int n);
		~Sales();

		void showSales()const;
	private:
		double sales[QUARTERS];
		double average;
		double max;
		double min;
	};
}

sales.cpp

cpp 复制代码
#include "sales.h"
#include "sales.h"
#include <iostream>

using namespace std;
using namespace SALES;

Sales::Sales()
{
	double sum = 0.0;
	for (int i = 0; i < QUARTERS; i++)
	{
		cout << "请输入第" << i + 1 << "个季度的销售额:";
		cin >> this->sales[i];
	}
	this->max = this->min = this->sales[0];
	for (int i = 0; i < QUARTERS; i++)
	{
		if (this->max < this->sales[i])
		{
			this->max = this->sales[i];
		}
		if (this->min > this->sales[i])
		{
			this->min = this->sales[i];
		}
		sum += sales[i];
	}
	
	this->average = sum / QUARTERS;
}
Sales::Sales(double ar[], int n)
{
	double sum = 0.0;
	if (n > QUARTERS)
	{
		for (int i = 0; i < QUARTERS; i++)
		{
			this->sales[i] = ar[i];
		}
	}
	else
	{
		for (int i = 0; i < n; i++)
		{
			this->sales[i] = ar[i];
		}
		for (int i = n; i < QUARTERS; i++)
		{
			this->sales[i] = 0;
		}
	}
	this->max = this->min = this->sales[0];
	for (int i = 0; i < QUARTERS; i++)
	{
		if (this->max < this->sales[i])
		{
			this->max = this->sales[i];
		}
		if (this->min > this->sales[i])
		{
			this->min = this->sales[i];
		}
		sum += sales[i];
	}

	this->average = sum / QUARTERS;
}
Sales::~Sales()
{

}

void Sales::showSales()const
{
	for (int i = 0; i < QUARTERS; i++)
	{
		cout << "第" << i + 1 << "个季度的收入为:"<<this->sales[i]<<endl;
	}
	cout << "最大销售额为:" << this->max << endl;
	cout << "最小销售额为:" << this->min << endl;
	cout << "平均销售额为:" << this->average << endl;
}

运行结果:

考查点:

  • 结构体到类的迁移

2024年9月4日15:28:22

相关推荐
懒大王爱吃狼1 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
秃头佛爷2 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨2 小时前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
XiaoLeisj4 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
dayouziei4 小时前
java的类加载机制的学习
java·学习
励志成为嵌入式工程师5 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉5 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer5 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq5 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
记录成长java7 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet