Type conversion from double to int. Never seen this difference [duplicate]

  algorithm, c++, numbers, typecasting-operator

I got double type value as int form like no decimal digit. But when I typecast that value to int, the value reduces by 1.

Like, val of type double, on calculation comes out to be 4. But when I typecast (int)val, then val becomes 3.

I believe there is some interesting answers for this.

CODE:

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        int a,b;
        cin>>a>>b;
        double res = log(a)/log(b);

        cout<<"res (double) "<<res<<"n";
        cout<<"res (int) "<<(int)res<<"n";
    }

    return 0;
}

Input

2
571787 83
445943744 764

Output

res (double) 3
res (int) 2
res (double) 3
res (int) 2

Source: Windows Questions C++

LEAVE A COMMENT