创建二维数组

To create two dimensional array

本文关键字:二维数组 创建      更新时间:2023-10-16

伙计们可以帮我做这段代码,因为我用了6个小时,仍然没有得到答案。

问题是"编写一个程序,创建一个二维数组(6*6),用1到100之间的随机数填充数组。a: 获取所有数字的总和b: 获取所有数字的平均值c: 确定行总数d: 确定行中的最高值e: 确定行中最低的

这是我的密码。

#include <iostream>
#include <ctime>
using namespace std;
// Main Function
int main()
{
    //Initialize Variables
    int table1[6][6];
    int highest ;
    int lowest ;
    double sumRow = 0;
    int row = 0;
    int col = 0;
    //PrintArray
    for (row = 0; row < 6; row++)
    {
        for (col = 0; col < 6; col++)
        {
            {
                table1[row][col] = rand() % 100 + 1;
            }
            cout << table1[row][col] << "t";
        }
        cout << "" << endl << endl;
    }
    //Highest & lowest value in the row
    for( row = 0; row <6; row ++)
    {    
        highest = table1[row][0];
        lowest = table1[row][0];
        for ( col = 0; col < 6; col++)
        {
            if ( highest < table1[row][col])
                highest = table1[row][col];
            if  (lowest > table1[row][col])
                lowest = table1[row][col];
            sumRow = sumRow + table1[row][col];
        }
        cout <<" Row" << row <<" highest value :" << highest <<endl;
        cout <<" Row" << row <<" lowest value  :" << lowest  << endl;
        cout <<" Row" << row <<" average value :" << sumRow/6 <<endl;
        cout <<" Row" << row <<" Total value   :" << sumRow  << endl;
        sumRow = 0;
        cout << endl;
    }
}

下面是一个可能的解决方案。请将此作为确定代码问题的参考。

#include <algorithm>
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int main(int argc, char* argv[])
{
  int table[6][6];
  int row_total[6];
  int row_max[6];
  int row_min[6];
  int total_total = 0;
  srand(time(NULL));
  for( int row = 0 ; row < 6 ; row++ ) {
    row_total[row] = 0;
    row_max[row] = numeric_limits<int>::min();
    row_min[row] = numeric_limits<int>::max();
    for( int col = 0 ; col < 6 ; col++ ) {
      table[row][col] = rand() % 100 + 1;
      row_total[row] += table[row][col];
      row_max[row] = max(table[row][col],row_max[row]);
      row_min[row] = min(table[row][col],row_min[row]);
    }
    total_total += row_total[row];
  }
  for( int row = 0 ; row < 6 ; row++ ){
    for( int col = 0 ; col < 6 ; col++ ){
      cout << std::right << std::setw(4) << table[row][col];
    }
    cout << "tTotal: " << std::right << std::setw(4) << row_total[row];
    cout << "tMax: " << std::right << std::setw(4) << row_max[row];
    cout << "tMin: " << std::right << std::setw(4) << row_min[row] <<      std::endl;
  }
  cout << "Total of all numbers: " << total_total << std::endl;
  cout << "Average of all numbers: "
    << setiosflags(ios::fixed | ios::showpoint)
    << setprecision(2)
    << total_total/36.0 << std::endl;
}