简体   繁体   中英

C++ floats being converted to ints

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.

函数的返回类型应为float而不是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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM