1

I am dividing 2 long values and use the ceiling of the result. However my code produces wrong output.

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

int main(){
  long first = 100;
  long second = 1000;
  long output = ceil(first/second);
  cout<<"output = "<<output<<endl;
}

Here the expected output is

output = 1

actual output:

output = 0

1 Answers1

3

Because of order of evaluation of long output = ceil(first/second);

The first operation is first/second, 100/1000. Once you are using integer types (long is an integer) the result will be a long and it is truncated towards zero. 100/1000 =0

Then you have: ceil(0) = 0 // as expected

long output = 0

user207421
  • 305,947
  • 44
  • 307
  • 483
MasterID
  • 1,510
  • 1
  • 11
  • 15
  • 1
    That makes a lot of sense. I did not realize the order of operations could affect the output like that. The solution turns out to be pretty simple as shown in the link @dxiv shared in the comments to my question. – Denis Shevchenko Jun 21 '20 at 00:41