bool testMagicSquare(string str) {
int length, sum = 0;
length = strlen(str);
for (int i = 0; i < length; i++) {
sum = sum + str[i];
}
if (sum == 120) {
return 1;
}
else return 0;
}
我的任务是从文本文件中获取十六进制方块,测试它是否是&#34; Magic Square&#34;。如果是,请在另一个文本文件中打印方块以保存它。 获取文本文件并打印到文件正在运行,但我仍然坚持测试。
有什么想法吗?
十六进制字符串示例:8 3 4 f 5 e 9 2 b 0 7 c 6 d a 1
答案 0 :(得分:1)
试试这段代码。它仅适用于一位数的十六进制数字!
#include <stdio.h>
#include <ctype.h>
#define DIMS 4
#define COLS DIMS
#define ROWS DIMS
int convertChar(unsigned char v);
int checkAndComputeSums(int *s , unsigned char *ms, int dim);
enum STYPE {
SUMROW,
SUMCOL,
SUMDIAG,
//-------------------
SUMCNT
};
unsigned char msqr[COLS][ROWS] = {
{'8','3','4','F'},
{'5','E','9','2'},
{'B','0','7','C'},
{'6','D','A','1'}
};
int sum[DIMS][SUMCNT];
const char * label[SUMCNT] = {
"ROWS","COLS","DIAG"
};
int convertChar(unsigned char v)
{
int x;
x = toupper((int)v);
x -= 48; /* 48 is the ASCII code of the char 0 */
if (x>9) x-=7;
return x;
}
int checkAndComputeSums(int *s , unsigned char *ms, int dim)
{
int i,j,ok=1;
/* The sum are cleared */
for(i=0;i<dim;i++) {
for(j=0;j<SUMCNT;j++) {
s[i*SUMCNT+j] =0;
}
}
for(i=0;i<dim;i++) {
for(j=0;j<dim;j++) {
s[i*SUMCNT+SUMROW]+=convertChar(ms[i*dim+j]);
s[i*SUMCNT+SUMCOL]+=convertChar(ms[j*dim+i]);
if (i==j)
s[SUMDIAG]+=convertChar(ms[i*dim+j]);
if (i==dim - j - 1)
s[SUMDIAG+SUMCNT]+=convertChar(ms[i*dim+j]);
}
if (s[i*SUMCNT+SUMROW]!=s[SUMROW] || s[i*SUMCNT+SUMCOL]!=s[SUMROW])
ok=0;
}
if (s[SUMDIAG]!=s[SUMROW] || s[SUMDIAG+SUMCNT]!=s[SUMROW])
ok=0;
return ok;
}
int main(void)
{
int i,j;
i=checkAndComputeSums(sum[0],msqr[0],DIMS);
printf("The check was %s\n",(!i)?"KO":"OK");
for (j=SUMROW;j<SUMCNT;j++) {
printf("%s: ",label[j]);
for(i=0;i<DIMS-((j==SUMDIAG)?2:0);i++) {
printf("%d ",sum[i][j]);
}
puts("");
}
return 0;
}