0:
#include <stdio.h>
int main()
{
int a, b, c, t;
int *pa, *pb, *pc;
printf("请输入三个数:");
scanf("%d %d %d",&a,&b,&c);
pa = &a;
pb = &b;
pc = &c;
if (a > b){
t = *pa;
*pa = *pb;
*pb = t;
}
if (a > c){
t = *pa;
*pa = *pc;
*pc = t;
}
if (b > c){
t = *pb;
*pb = *pc;
*pc = t;
}
printf("%d <= %d <= %d\n",*pa, *pb, *pc);
return 0;
}
1:
#include <stdio.h>
int main()
{
int i, j, n, sum, count = 0;
printf("请输入一个整数(大于2):");
scanf("%d",&n);
sum = n * n * n;
for (i = 1; i < sum; i += 2){
for (j = i; j < sum; j += 2){
count += j;
if ( sum == count ){
if ( j - i > 4){
printf("%d = %d + %d + ... + %d\n",sum, i, i+2, j);
} else {
printf("%d = %d + %d + %d\n",sum, i, i+2, j);
}
goto FINDIT;
}
if ( count > sum ){
count = 0;
break;
}
}
}
FINDIT:
return 0;
}
2:改进上一题的代码,用户输入一个表示范围的最大值 count,程序将测试 3 ~ count 所有的整数是否都符合尼科彻斯定理。附加要求:有些用户可能不希望看到打印一丢丢式子,所以是否打印应该让用户确定(提示 -> 用二维数组先保存结果)
#include <stdio.h>
#include <stdbool.h>
int main()
{
int i, j, n, count, cubed, sum = 0;
bool result = true; // 用于存放验证结果
char answer;
printf("请输入一个整数:");
scanf("%d", &count);
int array[count][4];
// 变长数组无法再定义是初始化,只能手动了...
for (n = 3; n < count; n++)
{
// 初始化第一列,因为后边用于验证
array[n][0] = 0;
}
for (n = 3; n < count; n++)
{
cubed = n * n * n;
for (i = 1; i < cubed; i += 2)
{
for (j = i; j < cubed; j += 2)
{
sum += j;
if (sum == cubed)
{
array[n][0] = cubed;
array[n][1] = i;
array[n][2] = i + 2;
array[n][3] = j;
goto FINDIT;
}
if (sum > cubed)
{
sum = 0;
break;
}
}
}
FINDIT:
sum = 0;
}
// 检查
for (n = 3; n < count; n++)
{
if (array[n][0] == 0)
{
result = false;
break;
}
}
if (result)
{
printf("经验证,3 ~ %d 之间所有的整数均符合尼科彻斯定理!\n\n", count);
printf("是否打印所有式子(y/n):");
getchar();
scanf("%c", &answer);
}
else
{
printf("验证失败:整数 %d 无法找到对应的连续奇数!\n");
}
if (answer == 'y')
{
// 打印
for (n = 3; n <= count; n++)
{
if (array[n][3] - array[n][1] > 4)
{
printf("%d^3 == %d == %d + %d +... + %d\n", n, array[n][0], array[n][1], array[n][2], array[n][3]);
}
else
{
printf("%d^3 == %d == %d + %d + %d\n", n, array[n][0], array[n][1], array[n][2], array[n][3]);
}
}
}
return 0;
}