-2

When I multiply a long long value with a double value, I get a double value.

To convert it back to long long, I use (long long).

But the output I get is 0, when it should be 10.

This is my code:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long n = 100;
    printf("%lld",(long long)0.1*n);

    return 0;
}

Why is this? How can I fix this?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187

2 Answers2

1

You are casting 0.1 to long long. Which is 0. This will work:

(long long) (0.1 * ...)
Kaveh Vahedipour
  • 3,412
  • 1
  • 14
  • 22
1

C-style casts have a higher operator precedence than arithmetic operators, like the multiplication operator.

So, in order to receive a non-zero result here, you'd have to put parentheses around the arithmetic expression to have it evaluated before the type conversion takes place.

For reference:

Quote from there (emphasis mine):

When parsing an expression, an operator which is listed on some row of the table above with a precedence will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it with a lower precedence.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187