[英]C++ floats being converted to ints
I have the following function that should return an average of l1 - l7 . 我有以下函数,应该返回平均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
. 因为您函数的返回类型是
int
。 Change it to float
and it'll work fine. 将其更改为
float
即可正常工作。
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
. 因为函数的返回类型是
int
。
So the result ttl/7.0
which will be a float
will be cast to an int
and then returned. 因此,将结果
ttl/7.0
(将是float
将转换为int
,然后返回。
Change the return type to float
to fix this. 将返回类型更改为
float
以解决此问题。
函数的返回类型应为float而不是int。
As others pointed out, changing the return type to float
instead of int
will yield a float
value.. 正如其他人指出的那样,将返回类型更改为
float
而不是int
将产生一个float
值。
To set the 2 digits precision setprecision ( int n )
, will be helpful... 设置2位数的精度
setprecision ( int n )
将很有帮助...
Also for precision, you can use ios_base::precision
... 同样为了精度,您可以使用
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.