1

i can't get cout to display decimals (using eclipse c++ and mingw)

#include <iostream>
using namespace std;

int main() {

    int a = 55, b = 60, c = 70;

    double avgResult;

    avgResult = ((a + b + c) / 3);

    cout << avgResult;  //should display 61.666666

    return 0;
}

my output is 61 when I would expect it to be 61.666666.

I can get it to display the decimals using

cout << std::fixed << std::setprecision(2) << avrResult;

but I thought I didn't need to do that unless I wanted a specific decimal precision.

If I do something like

double value = 12.345;
cout << value;

it displays correctly so it leads me to believe that the above problem has to do with the use of int values in my calculation of double avgResult

btw I am new to c++ and am just starting to learn

user1677657
  • 89
  • 1
  • 3
  • 13
  • 4
    Ah, an issue with integer math versus double math. We all did this exact same thing at one point! – AndyG Jun 13 '13 at 15:54

2 Answers2

12

((a + b + c) / 3) - that has an int type. Change it to ((a + b + c) / 3.0) to get double

Andrew
  • 24,218
  • 13
  • 61
  • 90
1

You compute (a + b + c) / 3 and then you store it in avgResult. avgResult is a double, but a + b + c is int, 3 is int, so the result of division is int. So you finally store an int in your double variable.

Another way to get a double result, besides the already mentioned one:

avgResult = a + b + c;
avgResult /= 3;
Sorin
  • 908
  • 2
  • 8
  • 19