我手头有一个问题,我无法弄清楚,因为我对 C 编程还很陌生。问题是找出100到999之间所有可以用(a^2 + b^2)形式表示的整数。
这是我尝试过的:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n,i,j,soln;
for (n=100;n<1000;++n) {
soln=0;
for (i=0;i<100;++i) {
for (j=i;j<100;++j) {
if ((i^2 + j^2)==n) {
soln=1;
} else {
soln=0;
}
}
}
if (soln==1) printf("%d is a solution.\n",n);
}
return EXIT_SUCCESS;
}
谢谢大家!
最佳答案
您的代码有两个问题:
<强>1。使用 *
对数字进行平方,而不是 ^
要在 C 中对数字求平方,请不要使用 ^
运算符(这是按位异或运算符)。请改用 *
运算符:
if ((i*i + j*j)==n) {
soln=1;
} else {
soln=0;
}
<强>2。将 if
条件移到内部循环中
您的代码的另一个问题是您覆盖了 soln
值。您应该将条件移动到内部循环中:
for (n=100;n<1000;++n) {
soln=0;
for (i=0;i<100;++i) {
for (j=i;j<100;++j) {
if ((i*i + j*j)==n) {
soln=1;
} else {
soln=0;
}
// Condition here. When it was in the outer loop level,
// the soln=1 would be overwritten to the 0 in the next iteration
// and printf() wouldn't be called.
if (soln==1) {
printf("%d is a solution.\n",n);
// To avoid printing multiple times for the same n,
// break from the loop (loop for 'j').
// If you would want to print for every i,j pair that meets
// the criteria, remove this 'if' block, get rid of 'soln'
// and print in the if above (where you square the numbers).
break;
}
}
// We need to break the two loops, for i and j. This one is for
// the outer loop ('i').
if (soln == 1) break;
}
}
如您所见,您可以通过两种略有不同的变体来实现:
您只关心
n
- 如果您不需要知道解的数字的组成部分,您可以加快速度通过不打印所有可能的解决方案,只打印满足它的n
来稍微改进算法。在那种情况下,一旦您找到一个i
和j
,当它们的平方为n
时,只需打破这两个循环。你可以这样做,因为对于n
,我们知道存在满足条件的i
/j
对。您关心的是
n
和解方程的确切i
/j
-在这种情况下,删除soln
变量并只打印解决方案,而不是将soln
设置为 1。
关于C - 找出数字的 a^2+b^2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259762/