简体   繁体   中英

Difference between x * 0.1 and x / 10?

I am a high school student and I saw a while ago that is better to multiply than to divide. Since then, without any proof found that it is true or not and without knowing how to do find it by myself at the moment, I tried to modify my codes for that slightly better time.

Here is a problem where I wanted to find the biggest digit in a number using recursion.

This one is working.

#include <iostream>

using namespace std;

int minn = 9;

int digit(int n)
{
    if(minn > n % 10)
        minn = n % 10;
    if(!(n / 10))
        return minn;
    else
        return digit(n / 10);
}

int main()
{
    int x;
    cin >> x;
    cout << digit(x);
    return 0;
}

But this is not working.

#include <iostream>

using namespace std;

int minn = 9;

int digit(int n)
{
    if(minn > n % 10)
        minn = n % 10;
    if(!(n * 0.1))
        return minn;
    else
        return digit(n / 10);
}

int main()
{
    int x;
    cin >> x;
    cout << digit(x);
    return 0;
} 

The only difference is that the broken one use if(.(n * 0.1)) not if(!(n / 10)) .

Can someone clarify it for me or anyone who is seeking help what is the difference between x * 0.1 and x / 10?

Thank you all for clicking the question and that you tried to help!

0.1 is a double type, 10 is an integer type.

When dividing two integers eg n / 10 you will get integer division (eg 6/10 will equal 0 ).

And your check will work differently when using 6 * 0.1 as that will equal 0.6 .

n *.1 results in a floating point result. So, 3 *.1 produces the result of .3 , which is definitely not 0.

On the other hand, 3/10 is 0. That's how integer division works in C++.

Can someone clarify it for me or anyone who is seeking help what is the difference between x * 0.1 and x / 10?

Difference is very significant. In the first case you use floating point multiplication in the second integer division. So first if() would happen when n == 0 while second when n < 10.

if( !(n*0.1) ) // for if to work result of n * 0.1 must be equal 0 which only happens when n == 0

if( !(n/10) ) // for if to work result of n / 10 must be equal to 0 which happens when abs(n) < 10 (including 0)

You define x as int , x*0.1 uses float arithmetics, while x/10 uses integer arithmetics

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