简体   繁体   English

硬编码二维数组值

[英]hardcoding 2D array values

Trying to insert values into a 2D array, but the output isnt giving my values, instead random letters试图将值插入二维数组,但输出没有给出我的值,而是随机字母

int myArr[8][2] = {700,730,760,790,810,840,910,1000}{0.011,0.035,0.105,0.343,0.789,2.17,20,145};
cout  << myArr << endl;
system("Pause");

How should I adjust the code, or is it easier to use a text file and insert?我应该如何调整代码,或者使用文本文件并插入更容易?

Numerous problems:无数的问题:

  • the array dimensions are wrong数组维度错误
  • you don't have outer braces or a comma for the nested arrays嵌套数组没有外大括号或逗号
  • you're trying to store double precision floating point values in an int array您正在尝试将双精度浮点值存储在int数组中
  • you can't use cout with an entire array.您不能对整个数组使用cout

The array declaration should probably be something like this:数组声明可能应该是这样的:

double myArr[2][8] = { {700,730,760,790,810,840,910,1000},
                       {0.011,0.035,0.105,0.343,0.789,2.17,20,145} };

and to output the contents you could do something like this:并输出内容,您可以执行以下操作:

for (int i = 0; i < 2; ++i)
{
    for (int j = 0; j < 8; ++j)
    {
        cout << " " << myArr[i][j];
    }
    cout << endl;
}

Live Demo现场演示

First - you can't print the whole array just by using cout << myArr , you need to iterate over the elements of the array using a for loop.首先 - 您不能仅使用cout << myArr打印整个数组,您需要使用for循环遍历数组的元素。

Second - you are trying to put decimal values into an integer array which will truncate all of the decimals.其次 - 您试图将十进制值放入一个整数数组中,该数组将截断所有小数。

Third - Your array should be sized myArr[8][2] not myArr[2][8] .第三 - 您的数组的大小应为myArr[8][2]而不是myArr[2][8] I'm surprised your compiler lets you get away with this.我很惊讶你的编译器让你逃脱了这个。 You should probably look into using a different compiler.您可能应该考虑使用不同的编译器。

You need to iterate through each row and column, otherwise you're just printing out the pointer value of the array handle.您需要遍历每一行和每一列,否则您只是打印出数组句柄的指针值。

for (int i=0;i<8;i++){
  for (int j=0;j<2;j++){
    cout << myArr[i][j] << " ";
  }
  cout << endl;
}
system("Pause");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM