【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

相关推荐
邓熙榆10 分钟前
Logo语言的网络编程
开发语言·后端·golang
S-X-S1 小时前
项目集成ELK
java·开发语言·elk
飞的肖1 小时前
日志(elk stack)基础语法学习,零基础学习
学习·elk
Johaden2 小时前
EXCEL+Python搞定数据处理(第一部分:Python入门-第2章:开发环境)
开发语言·vscode·python·conda·excel
dal118网工任子仪3 小时前
66,【6】buuctf web [HarekazeCTF2019]Avatar Uploader 1
笔记·学习
02苏_3 小时前
2025/1/21 学习Vue的第四天
学习
羊小猪~~4 小时前
MYSQL学习笔记(四):多表关系、多表查询(交叉连接、内连接、外连接、自连接)、七种JSONS、集合
数据库·笔记·后端·sql·学习·mysql·考研
约定Da于配置4 小时前
uniapp封装websocket
前端·javascript·vue.js·websocket·网络协议·学习·uni-app
东京老树根5 小时前
Excel 技巧15 - 在Excel中抠图头像,换背景色(★★)
笔记·学习·excel
ByteBlossom6666 小时前
MDX语言的语法糖
开发语言·后端·golang