【问题标题】:How Can I Find the MIN, MAX, SUM and AVG of A Sorted List如何找到排序列表的 MIN、MAX、SUM 和 AVG
【发布时间】:2015-11-23 15:17:46
【问题描述】:

该程序旨在从文件中读取元素,然后使用 shell 排序对这些元素进行排序,将排序后的元素保存到数组中,然后找到最小值、最大值、总和和平均值。

到目前为止,它会读取文件、对元素进行排序并将它们存储在一个数组中,但在那之后我无法找到最小值、最大值、总和和平均值。

到目前为止,这是我的代码:

#include <iostream>
#include <fstream>

#include "arrayListType.h"

using namespace std;

int main()
{
    ifstream inFile;
    ofstream outFile;

    inFile.open("text.txt");

    arrayListType<int> list;
    arrayListType<int> newList;

    int num, counter = 0, min, max, sum = 0, avg = 0;

    while (inFile >> num)
    {
        list.insertEnd(num);
    }

    inFile.close();

    outFile.open("out.txt");


    cout << "The list before sorting:" << endl;
    list.print();
    cout << endl;

    list.shellSort();

    cout << "The list after sorting:" << endl;
    list.print();
    cout << endl;

    list = newList;


    cout << endl;
    return 0;
}

【问题讨论】:

  • SergeyA 我知道如何使用循环。我只是不知道如何引用 newList 本身。

标签: c++ arrays sorting readfile


【解决方案1】:

如果列表是排序好的,那么:

min 是第一个元素

最大值是最后一个元素

sum是将所有元素相加

平均(假设你的意思是平均)是列表中元素的总和/数量

【讨论】:

  • 列表中元素个数为零时除外;在这种情况下,平均值可能也为零。
  • 实际上在这种情况下平均值是不确定的。南。但是,您是对的,任何适当的平均代码都应该为该用例定义行为。
  • 是的,它可能看起来毫无用处。我需要自己显示这些元素(即列表的最小值是:...)一个 while 循环来计算最小值,我会说 newList.top() 是例如堆栈或队列的情况。这就是我的困扰。
【解决方案2】:

不管有没有排序,你都可以使用蛮力法:

int minimum = MAX_INT;
int maximum = MIN_INT;
int sum = 0; 
unsigned int quantity = 0U;
Let p = start of list;
while (p != end of list)
{
  if (p->value < minimum) minimum = p->value;
  if (p->value > maximum) maximum = p->value;
  sum = sum + p->value;
  ++quantity;
  p = p->next;
}
double average = 0.0;
if (quantity != 0)
{
  average = (double)sum / (double) quantity;
}

编辑 1:
为了节省一些时间,您可以执行这些计算,minimummaximumsumquantity,同时您正在插入到列表中。

这提出了一个想法,即除非您要在计算平均值后处理这些值,否则列表是不必要的。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多