0

my expected result is average=73.5 ,i have set the type of average as double but it result 73 what's the problem?

  #include <iostream>
  using namespace std;

  int main(){
int x=0;
int total=0;
double average=0;
int counter=0;

cout<<"Question 1"<<endl<<"Enter integer(-100 to end);";
cin>>x;
 if (x!=-100)
 {
     for(;x!=-100;counter++)
     {
         total=total+x;
         cin>>x;
     }

      average = total/counter;
 }
 cout<<"The average is:"<<average<<endl;


 return 0 ;

}

Griwes
  • 8,805
  • 2
  • 43
  • 70
  • since `total` and `counter` are both `int`, the result of that calculation will be `int`. There are many ways to solve it - `(1.0*total)/counter` is one. – Floris Nov 03 '13 at 15:15

2 Answers2

2

You're doing integer calculations. Cast one of the integers to double:

average = ((double)total)/counter;
Maroun
  • 94,125
  • 30
  • 188
  • 241
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • Just for curiosity, would static_cast be preferable over (double)? – lolando Nov 03 '13 at 15:18
  • Just a syntactic difference. It's exactly the same in this case. – Yochai Timmer Nov 03 '13 at 15:23
  • 1
    @lolando: I would certainly prefer `static_cast(total)`: although in this case it does exactly the same, it would catch problems when it does _not_ the same, e.g., when the C-style cast would result in a `reinterpret_cast<...>()` or a `const_cast<...>()`. – Dietmar Kühl Nov 03 '13 at 15:25
1

Integer operations yield integers as result. In C and C++ they never yield floating point results. You need to involve a floating point value in the computation, e.g.

average = (1.0 * total) / counter;
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380