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