Я пробовал написать этот код для вывода магического квадрата нечетного порядка на основе ввода нечетного числа. Когда я вхожу в 1 или 3, он работает нормально. Всякий раз, когда я ввожу что-либо выше, например, 5, 7, 9, 11 и т. Д., Программа сбрасывает момент, когда я нажимаю клавишу ввода. Я просмотрел свой код, и я не могу определить, где проблема. Я не получаю сообщений об ошибках.сбой программ на определенных входах
Небольшое примечание: если вы знаете, что такое магический квадрат, мой алгоритм здесь (предоставленный нам профессором на английском языке для перевода на C++) не выводит правильные значения, так как они не все объединяются в один и тот же номер.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n; //n = order
cout << "Enter an odd integer for the order of the Magic Square: ";
cin >> n;
cout << endl;
if(n%2 == 0) //only allows program to accept odd numbers
{
cout << "The number you have entered is not odd" << endl;
return 0;
}
int x, y; //x and y access the columns and rows of the following matrix
int magicsquare[n][n]; //creates a n by n matrix to set up magic square
int counter, square = n*n; //square is upper boundary
for(x=0; x<n; x++) //initialize all spaces in matrix with zeros
{
for(y=0; y<n; y++)
magicsquare[x][y] = 0;
}
/*Beginning of the magic square algorithm*/
x = 0, y = n/2; //initialize algorithm at the middle column of the top row
for (counter = 1; counter <= square; counter++) //magic square will contain the integers from 1 to n squared
{
magicsquare[x][y] = counter; //places current counter number at current position in the matrix or square
x--; //moves position diagonally up
y++; //and to the right
/*If a move takes you above the top row in the jth column, move to the bottom of the jth column*/
if(x<0)
x = n - 1;
/*If a move takes you outside to the right of the square in the ith row, move to the left side of the ith row*/
else if(y==n)
y = 0;
/*If a move takes you to an already filled square or if you move out of the square at the upper right
hand corner, move immediately below position of previous number*/
else if((magicsquare[x][y] != 0) || (x<0 && y==n))
{
y--; //move one space to the left back into the square
x = x+2; //move two spots down into the square and below previous number
}
}
for(x=0; x<n; x++)
{
for(y=0; y<n; y++)
cout << setw(5) << magicsquare[x][y];
cout << endl;
}
return 0;
}
Опубликовать большой блок кода и сказать, что это «сбой» не помогает. Что именно происходит? Вы получили сообщение об ошибке? Какие? И можете ли вы использовать отладчик или использовать инструкции печати, чтобы хотя бы изолировать, где это происходит? –
Вы прошли через свой отладчик, чтобы узнать, что происходит? Какое исключение вы получаете? – adamdc78
@MarkLuna неясно, что вы намерены, но тот факт, что вы используете 'else if' в своем цикле, чтобы протестировать условия, которые уже были отсеяны, указывает на то, что в логике неверно. –