2016-03-13 87 views
0

当试图编译代码的g ++给了我这个错误:对于二维数组循环

#include<iostream> 

int main(){ 
    int coordinates[3][2]={{1,2}, 
          {5,2}, 
          {5,9}}; 
    for(int coordinate[2]:coordinates){ 
     std::cout<<coordinate[0]+coordinate[1]; 
    }; 
    return 0; 
}; 
+0

你对()循环是不正确的。你到底想要打印什么? –

+0

我想做一个象棋游戏和坐标数组是可能的运动,这个for循环是为了让棋盘瓦片可能的运动。 –

回答

0

好“数组必须用括号内的初始化初始化”,我可以清楚地看到你的代码中的问题。

在循环中,类型不是纯int,而是int *。你有两个选择,要么使用int *或自动

您的最终代码看起来应该行

int main(){ 
    int coordinates[3][2]= 
    { 
     {1,2}, 
     {5,2}, 
     {5,9} 
    }; 

    // You can use either int* or auto. 
    // I personally prefer auto 
    // as it's more cleaner. 
    // 
    // for(int *coordinate :coordinates){ 


    for(auto coordinate:coordinates){ 
     std::cout<<coordinate[0]+coordinate[1]; 
    }; 
    return 0; 
}; 
+1

允许使用额外的逗号。这不是一个错误。 – Simple

+0

坦克你!这解决了我的问题。 –

+0

@简单,对我来说是新的,但你是对的。谢谢 – Saleem