创建并迭代3D数组

时间:2015-10-12 20:57:39

标签: c++ arrays 3d

这是我的3D数组迭代。我无法收到所需的样本输出:

输入种子:22 6 11 4 错误。数组索引无效。

我究竟要把cout语句放在“错误。数组索引无效。”?为了匹配上面的输出?

#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;
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你的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;
}
相关问题