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,533
  • 2
  • 42
  • 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
  • 91,013
  • 29
  • 181
  • 233
Yochai Timmer
  • 46,349
  • 23
  • 142
  • 181
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
  • 145,940
  • 13
  • 211
  • 371