任何人都可以帮助我做这个代码,因为我用了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;
}
}
答案 0 :(得分:1)
以下是可能的解决方案。请将此作为参考来确定您的代码问题。
#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;
}