开发者

MAgic Square function C++

This is my last function for my magic square and for some reason it's giving me an error that there is "'[int]' for array subscript" but I don't know what that means, if someone could help explain what I have to do.

bool Square::is_magic()
{
    for (i = 0; i < size-1; i++)
    {
        if (sum_row[i] != sum_row[i+1])
            return false;

    if (sum_col[i] != sum_col[i+1])
        return false;
        }

    if (sum_row[0] != sum_col[0])
        return false;

    if (开发者_高级运维sum_row[0] != sum_maindiag[0])
        return false;

    if (sum_row[0] != sum_other[0])
        return false;

    return true;
}


Ok everybody was beginer at some time. I really recommend you to read one or two books focused on c++. (Personally I learned programming with "Learn c++ in 21 days", many complain but it was good start for me).

And for the code. Not sure that it's what you need, it should go like this:

bool Square::is_magic()
{
   int i;
   for (i = 0; i < size-1; i++)
   {
       if (sum_row[i] != sum_row[i+1])
          return false;

       if (sum_col[i] != sum_col[i+1])
          return false;
   }

   if (sum_row[0] != sum_col[0])
         return false;

   if (sum_row[0] != sum_maindiag[0])
         return false;

   if (sum_row[0] != sum_other[0])
         return false;

   return true;

}

Some comments:

  1. You don't need brackets for 1 command after if,for,while statement

  2. Suggest using if -> else if -> else. Here it doesn't matter because you jump out of function as soon as you find something not correct, but in case you would continue in code you would check other statements even if it wasn't necessary.

  3. Get used to some style, make your own or copy someone's. Personally I use brackets this way:

    if (something != somethingElse){ doSomeNastyThings(); doEvenMore(); }

Good luck..

Edit: added variable declaration int for statement, updated brackets (clever idea as last 3 if-s aren't using index)


If statements are formatted like this:

if (condition) {
  do_this()
}

not like this:

{
if (condition)
  do_this()
}

They way you're formatting your code you're closing your for loop after two lines, which I imagine is not what you're trying to do (since you're referring to var i afterwards).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜