1
   float percentrelation = Individualrelatonshipdegree / relationshipdegree * 100;

这个简单的操作返回0,而Individualrelationshipdegree变量的值是19,relationshipdegree是35。但它仍然返回0。不明白这个问题。任何帮助将不胜感激。

4

4 回答 4

4

You are doing integer division. try

float percentrelation = 
    1.0f * Individualrelatonshipdegree / relationshipdegree * 100;
于 2012-11-27T16:35:56.963 回答
4

只看计算顺序。您想将 19 除以 35。所以它是 0。然后将 0 和 100 相乘。它也是 0。
所以您可以尝试通过类型转换使该表达式的第一个变量浮动:

float percentrelation = (float)Individualrelatonshipdegree / relationshipdegree * 100;

UPD需要解释类型转换的时刻。计算顺序是从左到右。我们有一个规则,在使用整数(int、byte、long long 等)和 float(float、double 等)操作数时,它们都被强制转换为浮点类型。这就是为什么我们只需要在第一个操作数上进行一次类型转换。这就是为什么 1.0f * 的另一个答案your expression也可以正常工作的原因。只是两种不同的方式。

于 2012-11-27T16:38:37.870 回答
3

Are the two variables integers? If yes, you might want to cast them first.

float percentrelation = (float) Individualrelatonshipdegree / (float) relationshipdegree * 100;

Also, note that float is not very precise. Consider using decimal isntead.

于 2012-11-27T16:36:09.553 回答
0

看看float(C# 参考)

基本上你不见了.F

例如。float x = 2.5F/3.5;

于 2012-11-27T16:39:42.413 回答