[英]double division keeps giving me “inf”
I have a function which the return type is double. 我有一个返回类型为double的函数。
my return statement is 我的退货单是
return sum / (double)(weight/100);
where sum is a double and weight is a int. 其中sum为双精度,weight为int。 I wrote printf statements before the return to check the values sum was 25.000 and (double)(weight/100) gave me .500 我写了printf语句,然后返回以检查值总和为25.000,并且(double)(weight / 100)给了我.500
but the return statement gave me "inf" 但是返回声明给了我“ INF”
what is wrong with it ? 有什么问题吗?
You are doing integer division between weight
and 100. How about: 您正在weight
和100之间进行整数除法。如何:
return 100 * sum / weight;
With this way you multiply 100 and sum
and you get a double again since sum
is double. 用这种方法,您将100与sum
相乘,由于sum
是两倍,因此您又得到了两倍。 Then you divide the double result with the integer weight and you don't face the problem of integer division. 然后,将整数结果除以整数权重,就不会遇到整数除法的问题。
It looks like weight
is probably an integer, so weight/100
gives 0
, and sum / 0.0
gives inf
. 看起来weight
可能是整数,所以weight/100
给出0
,而sum / 0.0
给出inf
。 Just rewrite it as: 只需将其重写为:
return sum / (weight/100.0);
You have to cast the weight first to double. 您必须先将重量增加一倍。 Now it divides an int by 100 to a new int. 现在,它将一个整数除以100到一个新的整数。 (Which probably becomes 0) Then you cast it to a double and then you divide sum by this answers. (可能变为0)然后将其转换为双精度,然后将总和除以该答案。 I would change it to: 我将其更改为:
return sum / ((double)weight)/100;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.