gpt4 book ai didi

c++ - Visual Studio 不采用数组 : int magicSquare[n][n]?

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:53 25 4
gpt4 key购买 nike

我写了我的代码,我准备提交它,但老师将在 Visual Studio 2015 上测试它。每次我测试它时,它都会给我一个错误,这个 int magicSquare[n][n ] 错误,无法读取 n

我如何修改这部分以使 visual studio 从 n 读取这个数组?

我的代码:

 #include <iostream>
using namespace std;
// This function is to create the requested magic squares
int main()
{

int n;
//asking for n
cout << "Please enter an odd number" << endl;
cin >> n;

//checking in case n doesnt follow rules
if (n < 3 || n % 2 == 0)
{
cout << "Invalid Entry, Please re-enter an odd number that is 3 or larger " << endl;
}
else
{
// A function to generate odd sized magic squares

int magicSquare[n][n];

// Setting every slot to 0
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magicSquare[j][i] = 0;
}
}

// Initializing position to 1
int j = n / 2;
int i = n - 1;

// Setting each value to generate the magic square
for (int num = 1; num <= n * n; )
{
if (j == -1 && i == n)
{
i = n - 2;
j = 0;
}
else
{
//send to next number
// moving it to the right side
if (i == n)
i = 0;
//send to next number again
// moving it to the upper side
if (j < 0)
j = n - 1;
}
//second condition
if (magicSquare[j][i])
{
i -= 2;
j++;
continue;
}
else
//add the number
magicSquare[j][i] = num++;
//first condition
i++; j--;
}
//displaying sum of col/row
cout << "The sum of each row/col: " << n * (n*n + 1) / 2 << endl;
//Dispplaying magic square
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
cout << " " << magicSquare[i][j];
cout << "\n";
}

}
cout << endl;
//re running program
return main();
}

最佳答案

标准要求数组长度是一个可在编译时计算的值,以便编译器能够在堆栈上分配足够的空间。在您的情况下,您试图将数组长度设置为编译时未知的值。是的,我知道编译器应该知道它似乎很明显,但这里不是这种情况。编译器无法对非常量变量的内容做出任何假设。'n' 必须是一个常量值。

关于c++ - Visual Studio 不采用数组 : int magicSquare[n][n]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com