-2
#include <iostream>
using namespace std;
int main() {
  int a,b,c;
  cin >> a >> b >> c;
  cout << a/b*c;
  return 0;
}

For a=5 b=10 c=2 the output gives 0 which is obviously wrong. As far as I understood << / * are binary operators / and * "bond" stronger than << and for / and * it is calculated from the left to right so first 5 is devided by 10, then the result (0.5) is multiplicated with 2 which is 1 and that is delivered by << to cout.

So can anyone give me an explanation for that result (0)?

3 Answers3

2

This is the integer division issue: if a==5 and b==10, then a/b==0.

See the standard, Multiplicative operators [expr.mul]

For integral operands the / operator yields the algebraic quotient with any fractional part discarded

AlexD
  • 32,156
  • 3
  • 71
  • 65
1

This is the result of integer rounding. When integer division is performed any fractional remainder is simply cut off. So 2 / 3 == 0.

To keep the results as accurate convert use doubles or convert the variables to doubles in the expression. So something like this

static_cast<int>(static_cast<double>(a) / static_cast<double>(b) * static_cast<double>(c))

will result in the correct value.

phantom
  • 3,292
  • 13
  • 21
0

No its not wrong

Since all variables are integers.

5/10 is 0 in the integer world and that multiplied with 2 is still 0

9/10 is also 0 but 11/10 is 1

if you want something useful from this declare the variables as double instead or IOW:

int main() {
  double a,b,c;
  cin >> a >> b >> c;
  cout << a/b*c;
  return 0;
}
AndersK
  • 35,813
  • 6
  • 60
  • 86