Unexpected result with ceil() function

Viewed 96
#include <bits/stdc++.h>
using namespace std;

int main() {

    long long n,m;
    double ans;

    cin>>n>>m;

    ans=log(m)/log(n);

    cout<<ans<<" "<<ceil(ans);
}

**input**
581
196122941
**output**
3 4
**expected output**
3 3

This is a simple c++ code where the input is 2 integer number and i have to calculate the log division of those numbers and find the ceil() of that result. But when i give the following input it shows that the division result is 3 but the ceil() of that result is 4. But ceil(3) should give 3. Why is this happening?

1 Answers

The result is something like 3.0000000000000004441. cout prints only the first 6 digits. There is also some kind of rounding involved but it's not the usual rounding. On my machine 3.000005 is printed as 3 and 3.000006 is printed as 3.00001. Print more digits with

cout<< setprecision(20) << ans<<" "<<ceil(ans);
Related