所以,我试图让这个C代码工作。它编译,但产生不正确的输出。它应列出1和所选值之间的所有完美平方数。 它做错了,在经过多次试验和错误之后,我认为问题在于模数运算...就像它早期截断或做一些其他奇怪的事情一样。
// C Code
/*This program will identify all square numbers between one and a chosen integer*/
#include <stdio.h>
#include <math.h>
int main(){
int i, upper, square_int;
float square;
printf("This program will identify all square numbers between one and a chosen integer");
printf("Please enter the upper limit integer:");
scanf("%d", &upper);
upper = 13; /*scanf is the primary integer input method; this is here just to test it on codepad*/
for (i = 1; i<= upper; ++i) /*i want to run through all integers between 1 and the value of upper*/
{
square = sqrt(i); /* calc square root for each value of i */
square_int = square; /* change the root from float to int type*/
if (i % (int)square_int == 0) /*check if i divided by root leaves no remainder*/
printf("%d\n", i); /*print 'em*/
}
printf("This completes the list of perfect squares between 1 and %d",upper);
return 0; /*End program*/
}
键盘上的输出是:
This program will identify all square numbers between one and a chosen integerPlease enter the upper limit integer:1
2
3
4
6
8
9
12
This completes the list of perfect squares between 1 and 13
这当然是错的。我希望得到1分,2分,4分和9分。谁能指出我的搞砸了?
答案 0 :(得分:1)
您的模运算不正确。如果i = 6
square_int
将成为2
,因此i % (int)square_int
等于6 % 2
,从而导致0
。
您可以检查是否square_int * square_int == i
。
答案 1 :(得分:1)
这是一个更简单的算法
int i = 1;
while (i*i < upper)
{
printf("%d\n", i*i);
++i;
}
另一种方法是计算平方根,将其转换为int,并比较数字。
for (i = 1; i <= upper; ++i)
{
square = sqrt(i);
square_int = square;
if (square == (float)square_int)
printf("%d\n", i );
}
答案 2 :(得分:1)
你说你希望获得1, 2, 4, 9
,这意味着你不希望获得3
。
让我们看一下i == 3
:
sqrt(3) == 1.732051
(int) 1.732051 == 1
3 % 1 == 0
。
这意味着它实际上会做预期的事情,但不会检查数字是否为正方形。
检查数字是否为正方形的简单算法是:
sqrt_int = sqrt(i) + 0.5;
if (square_int * square_int == i)
printf("%d\n", i);