在C语言中,如何定义一个数字是否为平方数?

在C语言中,如何定义一个数字是否为平方数?,c,C,在C语言中,如何定义一个数字是否为正方形?例如,为了找到任何正整数的平方根,我们使用C语言中的sqrt()函数,该函数是在头文件中编写的 假设我们必须找到正整数x的平方根。该程序将使用C语言 #include <stdio.h> #include <math.h> int main() { int x; double sq; scanf("%d", &x); sq = sqrt(x); printf("%0.2f\n", s

在C语言中,如何定义一个数字是否为正方形?例如,为了找到任何正整数的平方根,我们使用C语言中的
sqrt()
函数,该函数是在
头文件中编写的

假设我们必须找到正整数x的平方根。该程序将使用C语言

#include <stdio.h>
#include <math.h>

int main()
{
  int x;
  double sq;

  scanf("%d", &x);    
  sq = sqrt(x);    
  printf("%0.2f\n", sq);

  return 0;
}
#包括
#包括
int main()
{
int x;
双平方米;
scanf(“%d”和&x);
sq=sqrt(x);
printf(“%0.2f\n”,sq);
返回0;
}

像这样,那么现在什么是确定一个数字是否为平方数的最佳方法呢?

一旦得到平方根,将结果转换为
int
,它将截断任何分数分量。然后将这个数字乘以它本身,检查它是否等于原始数字

int x = // some nonnegative number
double sq = sqrt(x);
int sq_int = (int)sq;
if (sq_int * sq_int == x) {
    print("%d is a square\n", x);
} else {
    print("%d is not a square\n", x);
}
例如,如果
x
为9,则
sq
为3.0。因此
sq_int
被设置为3,并且由于
3*3==9
为真,因此它打印
9是一个正方形

#include <stdio.h>
#include <math.h>

int main(void)
{
    double x;

    double sq;

    scanf("%lf",&x);

    sq = sqrt(x); 

    if( sq == (int)sq )
        printf("sq is a root\n");
    else
        printf("sq is not a root\n");

    return 0;
}
如果
x
为10,则
sq
为3.162277。。。。因此
sq_int
被设置为3(因为小数部分被截断),并且
3*3==10
为false,它打印
10不是正方形
#include <stdio.h>
#include <math.h>

int main(void)
{
    double x;

    double sq;

    scanf("%lf",&x);

    sq = sqrt(x); 

    if( sq == (int)sq )
        printf("sq is a root\n");
    else
        printf("sq is not a root\n");

    return 0;
}
#包括 内部主(空) { 双x; 双平方米; 扫描频率(“%lf”、&x); sq=sqrt(x); 如果(平方==(整数)平方) printf(“sq是根\n”); 其他的 printf(“sq不是根\n”); 返回0; }
是否要验证
sqrt
的结果?请澄清你的问题。什么数字是“数字”?理论上,每个数字都是一个平方数。因为sqrt(x)*sqrt(x)=x=@Raildex:不正确-没有负数是平方数。啊-我没看到。很公平:)如果我们使用复数,这是正确的如果
sq
发生的情况是,例如
703.00000000000001
,强制转换为int返回
703
,隐式转换为double返回
703.00000000000001
(一个
0
更多)?如果你使用整数的平方根的例子,你的论点会更有说服力。我检查了前100000000个平方根,在小数点后的四个零的序列中,发现了大约5000个。我又做了一次,一共5个零,结果一个也没有找到。所以,对于至少在1-100000000范围内的数字,使用这个是安全的。