0

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
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Aditya
  • 1
  • 1
    Unrelated to your question but please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude May 05 '21 at 05:21
  • 1
    If you change default precision of `std::cout` it would not be enigma anymore: https://ideone.com/X7WhwE#stdin – Slava May 05 '21 at 05:22
  • 1
    And don't do C-style casting in C++ (like `(int) res`). While it doesn't matter much in this case it's usually a sign that you're doing something wrong, which could lead to undefined behavior or otherwise come around and give you problems later. – Some programmer dude May 05 '21 at 05:22
  • When you're dealing with floating-point values that you expect will have no fractional part, try subtracting the value from what you expect and looking at the result. You'll find that `3 - res` is not 0. – Pete Becker May 05 '21 at 12:55

0 Answers0