0

Im just trying to take an average of the students marks that has entered for N number of students. I have used float also tried with double data type for mu variable but when i divide two integers sum of marks and total number of students n if i input the values say n=4 and those student marks as 1,2,3,4 total sum is 10 so now to calculate mu is 10/4 i should ideally get 2.5 but i am getting 2. I think im missing something here. I am using Ubuntu to run the program written

#include <iostream>
using namespace std;
int main(){

    int stddiv,n,a[600],i,sum=0;
    float mu = 0;
    
    cout << "Please enter the number of students"<<std::endl;
    cin>>n;
    
    for(i=0;i<=(n-1);i++)
    {
        cout << "Please enter the marks of student "<<i<<std::endl;
        cin>>a[i];
        
    }
    
        for(i=0;i<=(n-1);i++)
        {
            sum=sum+a[i];
        }
        
    mu = (sum/(n));
    
    cout << "sum is "<<sum<<std::endl;
    cout << "mu is "<<mu<<std::endl;
    
    
    return 0;
    }
    
JagaSrik
  • 700
  • 7
  • 23
  • 2
    You divide an `int` by an `int` so the result is automatically an `int`. You assign it to a `float` after that, but it is too late, the answer is already truncated. Cast one of the `int`s to a `float` before you do the division, to force the division to result in a `float`. – BoBTFish Jul 24 '20 at 11:23
  • Yep, thanks @yksisarvinen I was trying to find a good duplicate. – BoBTFish Jul 24 '20 at 11:26

0 Answers0