今天要和大家分享的还是和平方数有关的题目,相信很多人都能够在百度里边搜索到三组平方数,但是今天讨论得这道题目和我们传统见到的不太一样,下面笔者向大家详细阐述。
题目:把1,2,3,...,9这9个数字分成A,B,C三组,每组至少一个数字,使得这3组中的所有数字分别能够排列成平方数a,b,c(a<b<c).设计程序,求出所有满足要求的所有方法。
分析:刚拿到这道题的时候我就想到用三个循环来实现此题,不过在调试的时候出现了一个问题,就是AV(access violation)当时想了半天没找到原因,然后就又逐过程调试,最后找出了问题的缘由,我会在代码中注释该问题
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<memory.h>
int main()
{
int al, bl, cl;
int a, b, c;
char s1[10], s2[10], s3[10];
char s[20];
char str[10] = "123456789";
for (al = 1; al <= (int)sqrt(798 * 1.0); al++)
{
a = al*al;
itoa(a, s1, 10);
for (bl = al + 1; bl <=(int) sqrt(897 * 1.0); bl++)
{
b = bl*bl;
itoa(b, s2, 10);
for (cl = bl + 1; (int)cl <= sqrt(8765321 * 1.0); cl++)
{
memset(s, 0, sizeof(s));//出现AV的地方,memset原本写在循环的结尾不过这样会出错
int ok = 1;
c = cl*cl;
itoa(c, s3, 10);
strcat(s, s1);
strcat(s, s2);
strcat(s, s3);
if (strlen(s) != 9)
continue;
for (int i = 0; i < 9; i++)
{
if (strchr(s, str[i]) == NULL)
{
ok = 0; break;
}
}
if (ok)
printf("%d\t%d\t%d\n", a, b, c);
}
}
}
return 0;
}