Explicit typecasting in C++

Why is the output of average not coming in decimals.

#include
using namespace std;
int main() {
int n,num,i,sum=0;
float avg;
cin>>n;
i=1 ;
while(i<=n){
cin>>num;
sum=sum+num;
i=i+1;
}
cout<<"The sum is "<<sum<<endl;
avg = float(sum/n);
cout<<"The average is "<<avg<<endl;
return 0;
}

Hello Shubham,
This is because sum and n both are integers. int/int in c++ gives and int value. Typecasting int to float just adds a decimal point followed by a zero. For eg : if sum is 16 and n is 5 , sum/n will be 3. Therefore, avg will become 3.0 which will be displayed as 3 only. To obtain the answer in decimals, you need to typecast either sum or n using the following statement in place of avg= float(sum/n):
avg = (float)sum/n; I have made the change in your code in line 14. https://ide.codingblocks.com/s/85446
Hit like if you understood.

1 Like