【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

相关推荐
南宫生18 分钟前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
高山我梦口香糖33 分钟前
[react]searchParams转普通对象
开发语言·前端·javascript
sanguine__34 分钟前
Web APIs学习 (操作DOM BOM)
学习
冷眼看人间恩怨1 小时前
【Qt笔记】QDockWidget控件详解
c++·笔记·qt·qdockwidget
信号处理学渣1 小时前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客1 小时前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
Lenyiin1 小时前
第146场双周赛:统计符合条件长度为3的子数组数目、统计异或值为给定值的路径数目、判断网格图能否被切割成块、唯一中间众数子序列 Ⅰ
c++·算法·leetcode·周赛·lenyiin
jasmine s1 小时前
Pandas
开发语言·python
biomooc1 小时前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
骇客野人1 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言