简体   繁体   中英

How does double data type change the answer compared to int, by a huge amount in C++?

I was solving a problem "Count the number of digits in a factorial", and stored the answer in two data types int and double. The answers from both the datatypes are different, and the one stored in double was finally correct. How is this happening?

Here's the code:

        int n;
        cin>>n;
        double ans;
        int ans_int;
        double digits = 0;
        int digit_int = 0; 
        for (int i = 1; i<=n; i++) {
            digits += log10(i);
            digit_int += log10(i);
        }

        ans = floor(digits)+1;

        ans_int = floor(digit_int)+1; // This gives wrong answer. 

        cout<<ans<<endl;

If in the above code, I make digits as int, instead of double, I get an answer as 1 digit, in 5, instead of 3. similarly in other cases.

The problem lies in this line: digit_int += log10(i); . When i is less than 10, then its logarithm will be less than 1. Adding less than one to an integer will effectively add zero.

Converting a double number to int rounds it down to the nearest integer first. So if you add up say log10(x) for x ≤ 10 ≤ 99, the logarithm is always between 1 and 2, but converting to int will only add 1, instead of the correct value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM