开发者

C++ floats being converted to ints

开发者 https://www.devze.com 2023-01-19 23:08 出处:网络
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 place

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开发者_如何学运维; 
}


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);


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.


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


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...


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消