Regarding wrong ceil and floor values

Why there is wrong output of ceil and floor values in this code :

enter code here
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
float y = 99999980;
float z =-99999980;
ll x = ceil(y);
ll q = floor(z);
cout<<x<<endl<<q<<endl;
}

output is
99999984
-99999984

1 Like

@worldunique
Try these commands-
printf("%f\n",(float)99999980.0);
printf("%f\n",99999980.0);
printf("%f\n",x);
printf("%f\n",y);

printf("%.55f\n",10.1);
By default xxxx.xxx are treated as double in c/c++. when you save as float it is saved as 99999984.0
Due to small size of float. which often results in round off of floats.

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Round off section. As 99999980.0 is large number it is saved as 99999984.0 when stored in float data type.
And hence the reason for wrong input.
This is also the reason why using == operations with floats/double is not considered as safe.

3 Likes

can any one explain me why such thing is happening ?

yes that should be the reason . even when i am printing y and z

it is giving

1e+08
&
-1e+08

Thanks for the explanation !

Good answer. Nice!!

2 Likes

@vijju123 seen u after 3 days !!

Hmm. I can think of 3 instances-

  1. When you become a 7 star
  2. When you get a good placement and job from college and your parents start looking for your *dramatic cough*
  3. When you decide to give us all a treat :3 :stuck_out_tongue: :o
1 Like

Third one is the one i expect to be the sooner one of all three. @vijju123 :wink:

btw, Nice answer @aryanc403

2 Likes

Thank you @vijju123 @taran_1407 @worldunique
This was my first answer on codechef forum and got accepted.
Thank you.

2 Likes