0

我有一个学校项目。他们给了我一个需要在 10*10 的数组中的数据文件。这个数组需要是一个上三角形,这意味着对角线和对角线以下的所有值都必须为零。该数据文件是项目每个阶段所花费的时间。这意味着每个 [i][j] 代表阶段从 i 到 j 的时间。只是为了使问题更复杂,要求您找到每列的最长时间并将其添加到下一列中的最长时间。到目前为止,这是我的代码:

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

//Function prototype
int minCompletionTime (int Data[], int numTasks);

int main()
{
    //Declaring and initializing variables
    int num_Events(0), completion_Time(0);
    int startSearch(0), endSearch(0);
    const int SIZE(10);
    char datch;

    //Declaring an array to hold the duration of each composite activity
    int rows(0),duration_Data [10];

    //Declaring an input filestream and attaching it to the data file
    ifstream dataFile;
    dataFile.open("duration.dat");

    //Reading the data file and inputting it to the array. Reads until eof
    //marker is read
    while (!dataFile.eof())
    {
        //Declaring an index variable for the array

        //Reading data into elements of the array
        dataFile >> duration_Data[rows];

        //Incrementing the index variable
        rows++;

    }
    //Taking input for the number of events in the project
    cout << "Enter the number of events in the project >>> ";
    cin  >> num_Events;

    //Calling the function to calculate the minimum completion time 
    completion_Time = minCompletionTime(duration_Data, num_Events);

    //Outputting the minimum completion time
    cout << "The minimum time to complete this project is " << completion_Time
        << "." << endl;

}

int minCompletionTime (int Data[], int numTasks)
{
    int sum=0;
    //As long as the index variable is less than the number of tasks to be
    //completed, the time to complete the task stored in each cell will be 
    //added to a sum variable
    for (int Idx=0; Idx < numTasks ; Idx++)
    {
        sum += Data[Idx];
    }

    return sum;
}

任何帮助将不胜感激 我的数据文件只有 6 个元素包含这些元素:9 8 0 0 7 5 我的数据应该看起来像这样才能开始执行操作。

0 0 0 0 0 0 0 0 0 0 
0 0 9 8 0 0 0 0 0 0 
0 0 0 0 7 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0

这有点令人困惑。对不起。第一列和第二列应该以相同的方式具有零值和第一行。第五行之后也应该全为零,因为它将填充来自其他数据文件的更多信息。

4

1 回答 1

0

有几种方法可以解决这个问题。这里有2个非常幼稚的方法:

1. 使用 10x10 数组:

  • 从数据文件 ( dataFile >> data[row][col]) 中读取所有内容。
  • 有 2 个嵌套循环:
    • 外部循环遍历列。
    • 内部循环遍历该特定列的行。
    • 由于您必须找到最大值并且对角线下的值为零,因此您可以偷懒并找到每列的最大值(如果它比 10x10 大很多,您可能会遇到麻烦)。但是,如果您只想遍历必要的行,我会让您弄清楚(很简单,不要过度思考)。

2. 仅使用 1x10 数组:

  • 用最小值初始化数组(0 或 -1 应该适合你),我们称它为max_row.
  • 逐项读取每一行,并将其与存储在中的值进行比较,max_row并适当地替换。
  • 完成后,只需总结max_row.
于 2012-06-29T16:12:19.227 回答