-8

this is not working :

for(int i=a;i<=b;i++)  
{      
    if(sqrt(i)==int) count++;  
} 

What should I use?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

4 Answers4

1

Do something like below :

double a = 5, b = 25;
short count = 0;
for (double i = a; i <= b; i++) {
    double sqrut=sqrt(i); 
    if ((int)(sqrut) == sqrut) {
        printf("Perfect square %.0f found\n", i);
        count++;
    }
}
printf("Total number of perfect squares is %d\n", count);

or like below :

double a = 5, b = 25;
short count = 0;
for (double i = a; i <= b; i++) {
    int sqrut = sqrt(i); // An implicit casting happens here.
    if ((sqrut * sqrut) == i) {
        printf("Perfect square %.0f found\n", i);
        count++;
    }
}
printf("Total number of perfect squares is %d\n", count);
sjsam
  • 21,411
  • 5
  • 55
  • 102
0

One way to approach this is to truncate the root to an int and check if this affects the value:

double root = sqrt(i);
if ((int) root == root) {
    count++;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I wouldn't rely on that (accuracy issues). must be a duplicate, I found this for C++ (should work for C as well): https://stackoverflow.com/questions/23558888/checking-if-a-number-is-perfect-square – Jean-François Fabre Sep 02 '17 at 17:53
0

To see if a double has a fraction, use modf()

The modf functions break the argument value into integral and fractional parts, C11dr §7.12.6.12 2

double root = sqrt(x);
double int_part;
if (modf(root, &int_part) == 0.0) puts("root is a whole number");

Note that sqrt(x) only provides the nearest representable double to the mathematical square root of x and so may give approximately correct results as root.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1
double iii = 4.0000000000000006;

double eee = sqrt(iii);

int fff = eee;

printf("%d\n", (int)eee == eee);    // returns 1 - which is incorrect

printf("%d\n", fff * fff == eee);   // returns 0  -- correct answer
0___________
  • 60,014
  • 4
  • 34
  • 74