【C++ Primer Plus习题】10.4

大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←

问题:

这里是引用

解答:
main.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

#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

#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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值