0

It should return false when the number does not have perfect square, otherwise it returns the root. But in this code it returns the root all the time. E.g. Input 5, root 2.

main()
{

int i;
int number=0;
int result=0;

for(i=0; i<10; i++){
    printf("Testing:");
    scanf("%i",&number);


    result = isSquare(number);

    if(result==0)
        printf("Fail\n");
    else
        printf("%i\n",result);

}
}


int isSquare(int n)
{
float root = sqrt(n);
if (n == (int) n)
    return root;

else
    return 0;

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
redundant6939
  • 153
  • 3
  • 5
  • 16

2 Answers2

2

Instead of:

if (n == (int) n) // n is an integer (not necessarily a perfect square)

You meant:

if (root == (int) root) // root is an integer (so n is a perfect square)
Paul
  • 139,544
  • 27
  • 275
  • 264
1

Should not it be like this ?

int isSquare(int n)
{
float root = sqrt(n);
if (n == ((int) root)*((int) root)) //Better use floor() function
    return root;
else
    return 0;
}
Paul
  • 139,544
  • 27
  • 275
  • 264
batbaatar
  • 5,448
  • 2
  • 20
  • 26