所以我需要使用二维数组来实现这一点,我被困在第一列。。。在第一列中,有2.0到3.0的数字加上0.1。
见图
#include using namespace std;
int main()
{ int x[0][0] = {{2.00};
cout <<" x 1/x x^2 x^3 x^4"<<endl;
cout <<"---- ---- ---- --------"<<endl;
for (int i = 0.1; i < 3.0; ++i) {
return 0; }
好的,我们的目标是获得那些列x, 1/x, x^2, x^3, x^4
我们可以通过x[row][0] = 2.0 + (0.1 * row);
得到第一列x
for(int row = 0; row < 11; ++row)
x[row][0] = 2.0 + (0.1 * row); // update first column
这将迭代第0列(第一列(中的所有行
,意味着第一列中的每一行都等于2.0+(0.1乘以行的索引(
所以第二列1/x
刚好比第一列高1x[row][1] = 1 / x[row][0];
for(int row = 0; row < 11; ++row){
x[row][0] = 2.0 + (0.1 * row); // update first column
x[row][1] = 1 / x[row][0]; // update second column
}
因此,在获得第一列(索引0(中所有行的值后,
第二列中的行的值将为1/第一列中行的值x[row][1] = 1 / x[row][0];
现在最后三列x^2, x^3, x^4
只是第一列幂(2,3,4(
x[row][2] = pow(x[row][0], 2); // values of the 3rd column is first column power 2
x[row][3] = pow(x[row][0], 3); // values of the 4th column is first column power 3
x[row][4] = pow(x[row][0], 3); // values of the 5th column is first column power 4
我们只取第一列的值,并将其与列的索引相加(2、3、4是第3、4、5列的索引(
for(int row = 0; row < 11; ++row){
x[row][0] = 2.0 + (0.1 * row); // update 1st column
x[row][1] = 1 / x[row][0]; // update 2nd column
x[row][2] = pow(x[row][0], 2); // update 3rd column
x[row][3] = pow(x[row][0], 3); // update 4st column
x[row][4] = pow(x[row][0], 3); // update 5st column
}
最后三行我们可以用for loop 将它们缩短
for(int row = 0; row < 11; ++row){
x[row][0] = 2.0 + (0.1 * row);
x[row][1] = 1 / x[row][0];
for(int column = 2; column < 5; ++column)
x[row][column] = pow(x[row][0], column);
}
所以我们完成了,我们构建了像图片一样的矩阵
我写了完整的代码,给出了像图片一样的输出
#include <iostream>
#include <cmath> // pow
#include <iomanip> //setprecision, setw()
using namespace std;
int main()
{
double x[11][5];
for (int i = 0; i < 11; ++i)
{
x[i][0] = 2.0 + 0.1 * i;
x[i][1] = 1 / x[i][0];
for (int j = 2; j < 5; ++j)
x[i][j] = pow(x[i][0], j);
}
// print the matrix
cout << setprecision(2) << fixed; // Round numbers to two decimal places
cout <<" x 1/x x^2 x^3 x^4" << 'n';
cout <<"---- ---- ---- ----- -----n";
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 5; ++j)
cout << x[i][j] << setw(7);
cout << 'n';
}
return 0;
}
输出应为:
x 1/x x^2 x^3 x^4
---- ---- ---- ----- -----
2.00 0.50 4.00 8.00 16.00
2.10 0.48 4.41 9.26 19.45
2.20 0.45 4.84 10.65 23.43
2.30 0.43 5.29 12.17 27.98
2.40 0.42 5.76 13.82 33.18
2.50 0.40 6.25 15.62 39.06
2.60 0.38 6.76 17.58 45.70
2.70 0.37 7.29 19.68 53.14
2.80 0.36 7.84 21.95 61.47
2.90 0.34 8.41 24.39 70.73
3.00 0.33 9.00 27.00 81.00