问题:
解答:
main.cpp
#include <iostream>
#include "sales.h"
using namespace std;
using namespace SALES;int main()
{Sales s1, s2;double de[QUARTERS] = { 12.1,32.1,42.1,51.1 };setSales(s1, de, QUARTERS);showSales(s1);cout << endl;setSales(s2);showSales(s2);return 0;
}
sales.h
#pragma once
namespace SALES
{const int QUARTERS = 4;struct Sales{double sales[QUARTERS];double average;double max;double min;};void setSales(Sales& s, double ar[], int n);void setSales(Sales& s);void showSales(const Sales& s);
}
sales.cpp
#include "sales.h"
#include <iostream>using namespace std;
using namespace SALES;void SALES::setSales(Sales& s, double ar[], int n)
{double sum = 0;if (n >= QUARTERS){for (int i = 0; i < QUARTERS; i++){s.sales[i] = ar[i];}}else{for (int i = 0; i < n; i++){s.sales[i] = ar[i];}for (int i = n; i < QUARTERS; i++){s.sales[i] = 0;}}s.max = s.min = s.average = s.sales[0];for (int i = 0; i < QUARTERS; i++){sum += s.sales[i];if (s.max < s.sales[i]){s.max = s.sales[i];}if (s.min > s.sales[i]){s.min = s.sales[i];}}s.average = sum / QUARTERS;
}
void SALES::setSales(Sales& s)
{double ar[QUARTERS] = { 0.0 };int i = 0;do{cout << "请输入第" << i + 1 << "季度的销量:";cin >> ar[i];if (!cin){cin.clear();while (cin.get() != '\n'){continue;}cout << "输入有误,请重新输入:";cin >> ar[i];}i++;} while (i<QUARTERS);setSales(s, ar, QUARTERS);}
void SALES::showSales(const Sales& s)
{for (int i = 0; i < QUARTERS; i++){cout << "第" << i + 1 << "季度的销售额为: " << s.sales[i] << endl;}cout << "平均为: " << s.average << endl;cout << "最大值为: " << s.max << endl;cout << "最小值为: " << s.min << endl;
}
运行结果:
考查点:
- 命名空间
- 多文件
2024年9月2日20:56:02