创建二维数组
To create two dimensional array
伙计们可以帮我做这段代码,因为我用了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;
}
相关文章:
- 创建 std::string 的二维数组的最佳做法
- 在创建动态二维数组时,在A[i*c+j]中使用c有什么用,即c代表什么
- 如何在C++中创建二维数组的数组
- C++基于用户输入字符串长度创建二维数组
- 如何在 C++ 中的堆上创建二维数组
- 动态创建具有默认值的二维数组C++
- 如何在C++中创建给定大小的二维数组
- 如何为二维数组创建类
- C++:创建结构的二维数组
- 如何创建一个一维数组来容纳几个二维数组
- 创建二维数组
- 如何为抽象类创建二维数组
- 创建结构的二维数组会导致崩溃
- 用C++创建二维数组,并在MATLAB中使用
- 使用输入值创建二维数组的大小
- 如何在C++中创建动态二维数组
- 正在创建类的二维数组
- 用双指针创建的C++二维数组
- 为什么在尝试用c++创建二维数组时会出现此错误
- 使用二维数组创建矩阵