创建和迭代一个3D数组

Creating and iterating through a 3D array

本文关键字:一个 3D 数组 迭代 创建      更新时间:2023-10-16

这是我的3D数组迭代。我在接收所需的示例输出时遇到麻烦:

输入seed: 226 11 4错误。无效数组索引。

我应该把输出语句"错误。"无效的数组索引"?让它匹配上面的输出?

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;
int main(){
int seed;
unsigned int x,y,z;
int sum = 0;
// prompt user for seed
cout << "Enter seed: ";
cin >> seed;
// initiate rand function
srand(seed);
int arr[10][10][10];
for(int z = 0; z < 10; z++){
   for(int y = 0; y < 10; y++){
       for(int x = 0; x < 10; x++){
           arr[z][y][x] = rand() % 1000;
       }
     }
  }

cout << "Enter an index for x, y, and z: ";
cin >> x >> y >> z ;
while((x < 1 && x > 10 ) || (y < 1 && y > 10 ) || (z < 1 && z > 10 ) ){
   cin >> x >> y >> z;
}
for(unsigned int a = x; a < 10; a++){
   sum += arr[a][y][z];
}
for(int j = y + 1; j < 10; j++){
   if (y >= 10)
   {
    cout << "Error. Invalid array index.";
   }
   else if (y < 10)
   {
    sum += arr[x][j][z];
   }
 }
 for(int k = z + 1; z < 10; z++){
   sum += arr[x][y][k];
 }

 cout << sum << endl;
return 0;
}

不是说0也应该是有效的,但是在你的代码中它不是,所以在我的示例中它也不是。

可以是这样的:

do{
  cout << "Enter an index for x, y, and z: ";
  cin >> x >> y >> z ;
  if((x > 0 && x < 10 ) && (y > 0 && y < 10 ) && (z > 0 && z < 10 ))
     break;
  else
    cout<<"Invalid array index"<<endl;
} while(1);

你的while循环看起来很可疑。

while((x < 1 && x > 10 ) || (y < 1 && y > 10 ) || (z < 1 && z > 10 ) ){
   cin >> x >> y >> z;
}

这些条件都不成立。你不能让y > 10 && y < 1为真。所以你需要重新考虑这个逻辑。

此外,您的代码严格指定数组从0…9开始索引(10个元素)。因此,您需要确保验证的是正确的数字。

while(x < 0 || x >= 10 || y < 0 || y >= 10 || z < 0 || z >= 10) {
    cout << "Error. Invalid array index." << endl;
    cin >> x >> y >> z;
}