C Programming - Library Functions - Discussion

Discussion Forum : Library Functions - Find Output of Program (Q.No. 2)
2.
What will be the output of the program?
#include<stdio.h>
#include<math.h>

int main()
{
    float i = 2.5;
    printf("%f, %d", floor(i), ceil(i));
    return 0;
}
2, 3
2.000000, 3
2.000000, 0
2, 0
Answer: Option
Explanation:

Both ceil() and floor() return the integer found as a double.

floor(2.5) returns the largest integral value(round down) that is not greater than 2.5. So output is 2.000000.

ceil(2.5) returns 3, while converting the double to int it returns '0'.
So, the output is '2.000000, 0'.

Discussion:
18 comments Page 1 of 2.

Rakhi Sinha said:   5 years ago
GCC compiler is giving some garbage value instead of 0.

Swapnil Kudale said:   8 years ago
@Djv is correct.

Amarjeet said:   9 years ago
It prints 0 because doubles priority is higher than an integer.

That's why it prints 2.000000 and 0.

Cvam singh said:   1 decade ago
Please specify that it will return from right or left.

Prince Rambade said:   1 decade ago
Ok if i assume above explanation to be correct. Then pls explain how below program result in,

Output : 0,0.00000000 ?

int main()
{
float i = 2.5;
printf("%d, %f", floor(i), ceil(i));
return 0;
}

ceil() returns a double & I have printed the value with %f format specifier but it results in 0.000000 how ?

Ganesh singh said:   1 decade ago
I have got the o/p=0; but now I am confused with the concept used in the following case given below:

int main()
{
double a=3;
int b=a;
printf("%d",b);
}

Please make me understood soon as possible.

Ramya said:   1 decade ago
Ceil always return double value. But here return type is integer while converting double to integer 8 bytes is converted to 4 byte real value. So four bits from right to return zero.
(1)

DJV said:   1 decade ago
ceil(2.5) returns '3'.

As double is 8 bytes- 3 is represented as :

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000011

So while converting double to int(which is of 4 bytes).

The first four bytes will be taken into consideration.

Hence returning the value '0' :).
(5)

Shubham said:   1 decade ago
This is really confusing. Please somebody explain clearly.

Raghav said:   1 decade ago
Double is 8 bytes and Int is 4 bytes. Hence specifying %d will yield in first 4 bytes from right which is Zero.
(1)


Post your comments here:

Your comments will be displayed after verification.