|
发表于 2019-10-7 20:23:05
|
显示全部楼层
本帖最后由 superbe 于 2019-10-7 20:45 编辑
可以这样:
#include <stdio.h>
int main()
{
int a,iSum = 0,i,j,k,cubed;
char b;
printf("请输入一个整数:");
scanf("%d", &a);
printf("经验证,3 - %d 之间所有的整数均符合尼科彻斯定理!", a);
printf("是否打印所有式子(y/n):");
getchar();
scanf("%c", &b);
//cubed = (a * a*a);
if (b == 'y')
for (k = a; k >= 3; k -= 1)
{
int found=0;
cubed = (k*k*k);
for (j = 1; j < (cubed); j += 2){
for (i = j; i <= (cubed);)
{
iSum += i;
if (iSum == cubed)
{
printf("%d ^3 = %d + %d ... + %d\n", k, j, j + 2, i);
found = 1;
break;
}
if (iSum > cubed)
{
iSum = 0;
break;
}
i += 2;
}
if(found) break;
}
}
else
{
return 0;
}
}
或者这样,用goto:
#include <stdio.h>
int main()
{
int a,iSum = 0,i,j,k,cubed;
char b;
printf("请输入一个整数:");
scanf("%d", &a);
printf("经验证,3 - %d 之间所有的整数均符合尼科彻斯定理!", a);
printf("是否打印所有式子(y/n):");
getchar();
scanf("%c", &b);
//cubed = (a * a*a);
if (b == 'y')
for (k = a; k >= 3; k -= 1)
{
cubed = (k*k*k);
for (j = 1; j < (cubed); j += 2)
for (i = j; i <= (cubed);)
{
iSum += i;
if (iSum == cubed)
{
printf("%d ^3 = %d + %d ... + %d\n", k, j, j + 2, i);
goto nextk;
}
if (iSum > cubed)
{
iSum = 0;
break;
}
i += 2;
}
nextk:;
}
else
{
return 0;
}
}
上面代码在计算下一个k之前前没有把iSum清0; 但结果是正确的。还是加上比较清楚。 |
|