tags:

views:

111

answers:

5

I have the following function that should return an average of l1- l7. However, it seems to only return an integer. Why is it doing this, and how do I make it return a float rounded to 2 decimal places?

Snippet:

int lab_avg(int l1,int l2,int l3,int l4,int l5,int l6,int l7) {
    float ttl;
    ttl = l1 + l2 +l3 +l4 +l5 +l6 +l7;
    return ttl / 7.0; 
}
+8  A: 

Because your function's return type is an int. Change it to float and it'll work fine.

Also, if you just want to print 2 decimal places, use an appropriate format in your output function. You don't need to do anything with the float itself:

printf("%.2f", some_value);
casablanca
+2  A: 

Because the function return type is int.
So the result ttl/7.0 which will be a float will be cast to an int and then returned.

Change the return type to float to fix this.

codaddict
A: 

the return type of your function should be float instead of int.

scatman
+1  A: 

As others pointed out, changing the return type to float instead of int will yield a float value..

To set the 2 digits precision setprecision ( int n ) , will be helpful...

Also for precision, you can use ios_base::precision...

liaK
@ Downvoters, Thanks for the comments.. It was really helpful... :P
liaK
+1  A: 
float ttl;
float lab_avg(int l1,int l2,int l3,int l4,int l5,int l6,int l7) 
 {

 ttl = l1 + l2 +l3 +l4 +l5 +l6 +l7;
 return (ttl/7); 
 }

int main()
 {
  lab_avg(11,12,13,14,15,16,17);
   printf("%.2f", ttl);
  return 0;
}
BE Student