【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

相关推荐
Alive~o.0几秒前
Go语言进阶&依赖管理
开发语言·后端·golang
Chef_Chen2 分钟前
从0开始学习机器学习--Day33--机器学习阶段总结
人工智能·学习·机器学习
花海少爷2 分钟前
第十章 JavaScript的应用课后习题
开发语言·javascript·ecmascript
手握风云-3 分钟前
数据结构(Java版)第二期:包装类和泛型
java·开发语言·数据结构
喵叔哟23 分钟前
重构代码中引入外部方法和引入本地扩展的区别
java·开发语言·重构
尘浮生29 分钟前
Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
hopetomorrow42 分钟前
学习路之压力测试--jmeter安装教程
学习·jmeter·压力测试
hopetomorrow43 分钟前
学习路之PHP--使用GROUP BY 发生错误 SELECT list is not in GROUP BY clause .......... 解决
开发语言·学习·php
小牛itbull1 小时前
ReactPress vs VuePress vs WordPress
开发语言·javascript·reactpress
怀澈1221 小时前
高性能服务器模型之Reactor(单线程版本)
linux·服务器·网络·c++