Home > Enterprise >  How ceil function works in c ?
How ceil function works in c ?

Time:11-20

When I execute this code the value of ans1, ans2 is 50002896 and 50005000.
I know there is some issues with ceil function but was not able to figure out the exact cause.

#include <bits/stdc  .h>
using namespace std;
int main()
{
      long long ans1 = 0, ans2 = 0;

      for (long long i = 1; i <= 10000; i  )
      {
            ans1 = ans1   ceil((float)i / 1);
            ans2 = ans2   i;
      }
      cout << ans1 << " " << ans2 << endl;
}

CodePudding user response:

The source of the problem is not the ceil function, but rather that not all integers can be represented accuratly as floating point values. Some more info about floating point representation: Wikipedia IEEE 754.

The following code is a minimal demonstration of the same issue that causes your issue:

float f1 = 100000000;
f1  ;
std::cout << std::to_string(f1) << std::endl;

[Wrong] Output (expected: 1):

100000000.000000

One approach would be to use double instead of float.
This will not solve the principle issue, but will make the range of representable integers a lot bigger:

double f1 = 100000000;
f1  ;
std::cout << std::to_string(f1) << std::endl;

Output:

100000001.000000

A side note: better to avoid #include <bits/stdc .h>, see: Why should I not #include <bits/stdc .h>?.

CodePudding user response:

First, try to use specific headers like #include , in this case, .because #include <bits/stdc .h> will bring lots of junk.

So the issue is with float not ceil explained below

floating-point values do not represent exact values.

Code:-

#include <iostream>
#include <iomanip>
using namespace std;

// Driver Code
int main()
{
    float num1 = 10000.29;
    float num2 = 10000.2;

    // Output should be 0.0900000000
    cout << std::setprecision(15)
        << (num1 - num2);
    return 0;
}

Output :-

0.08984375

  • Related