c++任务看一下,简单的代码运用

编写商品信息显示和处理的程序,显示5个不同商品的信息,信息包括商品名称、商品价格(10~100区间自定)、商品厂家、商品出场日期。
要求:
1.求5件商品的平均价格,输出平均价格;
2.找出价格最低、最高的商品,输出其信息;
3.找出平均价格在50元以上的商品,并输出其信息。
4.找出平均价格在70元以下的商品,并输出其信息。
5.找出价格高于平均价的商品,并输出其信息。
应该编写5个函数实现上述5个要求。

用结构体存放商品信息, 用循环判断输出其信息

你题目的解答代码如下:

#include <iostream>
#include <iomanip>
using namespace std;

struct dut
{
    char name[50];
    float price;
    char manufacturer[50];
    char date[50];
};

float getavg(struct dut a[], int n)
{
    int i;
    float avg, sum = 0;
    for (i = 0; i < n; i++)
        sum += a[i].price;
    avg = sum / n;
    return avg;
}

void getmaxandmin(struct dut a[], int n)
{
    int i, max = 0, min = 0;
    for (i = 1; i < n; i++)
    {
        if (a[i].price > a[max].price)
            max = i;
        if (a[i].price < a[min].price)
            min = i;
    }
    cout << "价格最低的商品:" << endl;
    cout << setw(17) << a[min].name << setw(8) << a[min].price << setw(20) << a[min].manufacturer << setw(13) << a[min].date << endl;
    cout << "价格最高的商品:" << endl;
    cout << setw(17) << a[max].name << setw(8) << a[max].price << setw(20) << a[max].manufacturer << setw(13) << a[max].date << endl;
}


void getmin50(struct dut a[], int n)
{
    cout << "价格在50元以上的商品:" << endl;
    int i;
    for (i = 0; i < n; i++)
    {
        if (a[i].price >50)
            cout << setw(17) << a[i].name << setw(8) << a[i].price << setw(20) << a[i].manufacturer << setw(13) << a[i].date << endl;
    }
}

void getmax70(struct dut a[], int n)
{
    cout << "价格在70元以下的商品:" << endl;
    int i;
    for (i = 0; i < n; i++)
    {
        if (a[i].price <70)
            cout << setw(17) << a[i].name << setw(8) << a[i].price << setw(20) << a[i].manufacturer << setw(13) << a[i].date << endl;
    }
}
void getavgup(struct dut a[], int n)
{
    cout << "价格高于平均价的商品:" << endl;
    int i;
    int avg = getavg(a, n);
    for (i = 0; i < n; i++)
    {
        if (a[i].price > avg)
            cout << setw(17) << a[i].name << setw(8) << a[i].price << setw(20) << a[i].manufacturer << setw(13) << a[i].date << endl;
    }
}

int main()
{
    struct dut a[5];
    for (int i = 0; i < 5; i++)
    {
        cin >> a[i].name >> a[i].price >> a[i].manufacturer >> a[i].date;
    }
    cout << "平均价格" << getavg(a, 5) << endl;
    getmaxandmin(a,5);
    getmin50(a,5);
    getmax70(a,5);
    getavgup(a,5);

    return 0;
}

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img