创建和迭代一个3D数组
Creating and iterating through a 3D array
这是我的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;
}
相关文章:
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如何使用条件计算 3D 网格中从一个点到另一个点的所有路径
- OPENCV是否有一个软件包将3D点转换为2D自上而下的视图
- 围绕另一个 3D 点旋转一个 3D 点
- 将分配给一个3D阵列
- Opengl 创建一个 3D 框而不是一个简单的三角形
- 在C++中循环遍历一个3d索引的1d数组
- 尝试创建一个 3D 矢量,该矢量将保留指向指向无符号字符的指针的指针
- 无法将一个 3D 矩阵转换为另一个 3D 矩阵
- 用C++制作一个简单的3D图形引擎有多难
- 在opengl- c++中创建一个3d游戏表面/游戏板
- 在openSceneGraph中设计一个3D房间
- 创建和迭代一个3D数组
- 如何改变xyz顺序时,使用一个扁平的3D数组
- 如何使用c++中的Eigen库创建一个高效的3D矩阵
- 使用一个动态分配的内存块创建2d或3d数组
- 在c++ 3D中计算一个矩形是否与一条射线相交
- 如何适应一个平面到一个3D点云
- 在c++中洗牌一个3d数组
- 输出一个3D数组的c++代码