this is not working :
for(int i=a;i<=b;i++)
{
if(sqrt(i)==int) count++;
}
What should I use?
this is not working :
for(int i=a;i<=b;i++)
{
if(sqrt(i)==int) count++;
}
What should I use?
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);
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++;
}
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
.
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