应详细说明求和部分的输出。但是我不知道要这么做。
int main()
{
cout << "This program is to find the sum of two Different arrays";
cout << endl;
// variable declaration
int Sizer = 0, Sizec = 0, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of rows for array: ";
// input
cin >> Sizer;
cout << "Enter the number of columns for an array: ";
cin >> Sizec;
cout << endl;
cout << "Enter the elements of first Array";
cout << endl;
// nested loop execution and input
for (int c = 0; c < Sizer; c++)
{
for (int d = 0; d < Sizec; d++)
{
cout << "Enter elements of array [" << c + 1 << "]" << "[" << d + 1 << "]: ";
cin >> first[c][d];
}
}
cout << endl;
cout << "Enter the elements of second Array";
cout << endl;
// nested loop and execution
for (int c = 0; c < Sizer; c++)
{
for (int d = 0; d < Sizec; d++)
{
cout << "Enter elements of array [" << c + 1 << "]" << "[" << d + 1 << "]: ";
cin >> second[c][d];
}
}
// outputting a sum
cout << endl;
cout << "Sum of Arrays: ";
cout << endl;
// loop execution and sum
for (int c = 0; c < Sizer; c++)
{
cout << "[";
for (int d = 0; d < Sizec; d++)
{
cout << first[c][d];
if (d != Sizec - 1)
cout << " ";
}
cout << "]";
if ( Sizer== Sizer / 2)
{
cout << "+";
}
else
{
cout << " ";
}
cout << "[";
for (int d = 0; d < Sizec; d++)
{
cout << second[c][d];
if (d != Sizec - 1)
cout << " ";
}
cout << "] ";
// output sum
cout << "[";
for (int d = 0; d < Sizec; d++)
{
sum[c][d] = first[c][d] + second[c][d];
cout << sum[c][d];
if (d != Sizec - 1)
cout << " ";
}
cout << "]";
cout << endl;
}
}
我需要一些如图所示。谁能帮我提供代码。
[2 3 5] [2 5 0] [4 8 5]
[1 2 3] + [4 8 1] = [5 10 4]
[1 4 2] [4 1 2] [5 5 4]
我刚刚更正了它。但我不知道如何以上述形式表示 知道你能帮我吗 我添加了一些行。所以这是我的新代码,我修复了一些部分,仅在添加+和=符号时遇到了问题,我知道它必须执行无行或无行大小的操作
答案 0 :(得分:2)
您可以调整输出顺序,并使用std::setw()来组织输出。
cout
的工作方式。在您的示例中,第一个输出应为[2 3 5] [2 5 0] [4 8 5]
代替
[2 3 5]
[1 2 3]
[1 4 2]
通过这种方式,输出顺序应该是
1: [a[0][0] a[0][1] a[0][2]] [b[0][0] b[0][1] b[0][2]] [c[0][0] c[0][1] c[0][2]]
为清楚起见,输出代码应为
for (int i = 0; i < Sizer; i++)
{
// output first matrix
cout << "[";
for (int j = 0; j < Sizec; j++)
cout << first[i][j] << " ";
cout << "]\t";
// output the second
cout << "[";
for (int j = 0; j < Sizec; j++)
cout << second[i][j] << " ";
cout << "]\t";
// output sum
cout << "[";
for (int j = 0; j < Sizec; j++)
cout << sum[i][j] << " ";
cout << "]\n";
}
将上面的代码添加到代码的末尾,我们可以在下面获得输出
[1 2 3 ] [1 1 1 ] [2 3 4 ]
[4 5 6 ] [1 1 1 ] [5 6 7 ]
[7 8 9 ] [1 1 1 ] [8 9 10 ]
您可能需要进行计算,以确定何时cout
和+
和=
。
10
比数字<10占用更多的空间,而且您也可能会得到这样的输出[1 2 3 ] [1 1 1 ] [2 3 4 ]
[4 50 6 ] + [1 1 1 ] = [5 6 7 ]
[7 8000 9 ] [1 1 1 ] [8 9 10 ]
为避免这种情况,我们可以为每个数字预设一些空间,例如,在数字setw(4)
之前添加cout
cout << setw(4) << first[i][j];
将在下面获取输出
[ 1 2 232] [ 1002301 21] [ 1012303 253]
[ 12 1 1] [ 2 343 1] [ 14 344 2]
[ 1 1 1] [ 2 3 1] [ 3 4 2]
这可能对您有用。