gpt4 book ai didi

c++ - 一些数字的幻方错误放置

转载 作者:行者123 更新时间:2023-11-30 03:25:39 24 4
gpt4 key购买 nike

我尝试创建一个简单的 3x3 幻方。 3x3 幻方由连续的整数(从 1 开始到 9 结束)组成,这些整数被放置在“n”行“n”列中,因此所有行、所有列和两条对角线的总和都相同。

我的算法是 1 up,1 left。

我的问题是,我很难弄清楚为什么我不能保留我以前的数字,如果下一列被数字占用,我就减 1。提前谢谢你

#include <iostream>
using namespace std;

int main ()
{
int magicsq[3][3];
int i,j,x;

int row=0; //start positon of row
int col=3/2; // and colum

for( i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
magicsq[i][j] = 0; //initialize to 0 your matrix
}
}

magicsq[row][col] = 1; //position to star the counting

for(x=2;x<3*3;x++)
{
row--;
col--;

if(row<0){
row=row+3;
}

if(col<0){
col=col+3;
}
if(magicsq[row][col]!=0)
{

row++; //i think this is where im having trouble

}

magicsq[row][col] = x;
}

for( i = 0; i<3;i++){
for(j = 0; j<3;j++)
{
cout<<magicsq[i][j] <<" ";
}
cout<<endl;
}
}

最佳答案

除以整数问题;就这样。 3/2 是 1。

if(magicsq[row][col!=0]) 也是有效的(所选列将为 0 或 1),但我认为您的意思是 if(!magicsq [行][列])

关于c++ - 一些数字的幻方错误放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888716/

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