C++ 数组值
Posted
技术标签:
【中文标题】C++ 数组值【英文标题】:C++ Array Value 【发布时间】:2020-11-26 09:23:22 【问题描述】:我试图在程序结束时找出 A、B 和 C 的值。当我尝试使用 for 循环计算时,我得到了一个完整的值列表。我只需要一个矩阵格式。
#include <iostream>
using namespace std;
int main()
int m = 3;
int A[m] [m] = ;
int B[m] [m + 1] = ;
int C[m + 1] [m] = ;
int counter = 0, k = 2;
for (int i=1; i<=m; i++)
for (int j=1; j<=m; j++)
A[i-1][i-1] = counter;
B[i][j] = counter;
C[j-1][j-1] = k;
counter++;
k += 3;
//Printing C
//get array columns and rows
int rows = sizeof C/ sizeof A[0];
int cols = sizeof C[0] / sizeof(int);
// Print 2d Array
cout << "your_array data "<<endl<<endl;
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
std::cout << C[i][j] << std::endl;
return 0;
【问题讨论】:
您发布的代码中没有cout
。请在问题中包含有问题的代码的minimal reproducible example 以及实际和预期的输出
int A[m] [m] = ;
不是标准 C++,而是编译器扩展。对可变大小的数组使用std::vector
。
请阅读Why aren't variable-length arrays part of the C++ standard?。应该是const int m = 3;
@JHBonarius 实际上大小是恒定的3
/4
。不用std::vector
,可以认为是错别字
你必须自己做一些工作来制作矩阵。 C++ 不是 matlab 或 python。你可以使用像 Eigen 或 Boost UBLAS 这样的库。
【参考方案1】:
您的A
和C
是
int A[3][3] = ;
int C[4][3] = ;
那你就用
int rows = sizeof C/ sizeof A[0];
int cols = sizeof C[0] / sizeof(int);
获取它的大小。那是
int rows = 3;
int cols = 4;
然后在循环中
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
std::cout << C[i][j] << std::endl;
您已交换了 rows
和 cols
的值。 C
是 int C[4][3];
不是 int C[3][4];
。
如果您想在一行中打印多个元素,您只需移动 std::endl
以仅在一行之后添加新行:
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
std::cout << C[i][j] << " ";
std::cout << "\n";
还要注意这不是标准的 C++
int m = 3;
int A[m] [m] = ;
int B[m] [m + 1] = ;
int C[m + 1] [m] = ;
阅读Why aren't variable-length arrays part of the C++ standard?了解更多信息。
【讨论】:
【参考方案2】:`
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
cout<<C[i][j]<<" ";
cout<<"\n";
` std:: 是不必要的,因为你有 using namespace std; 你不必做 endl 因为这样做你会在下一行打印下一个值。所以你必须把另一个 cout 放在嵌套循环之外。
【讨论】:
你应该解释你的答案。不只是为他做功课。以上是关于C++ 数组值的主要内容,如果未能解决你的问题,请参考以下文章