float percentrelation = Individualrelatonshipdegree / relationshipdegree * 100;
这个简单的操作返回0,而Individualrelationshipdegree变量的值是19,relationshipdegree是35。但它仍然返回0。不明白这个问题。任何帮助将不胜感激。
You are doing integer division. try
float percentrelation =
1.0f * Individualrelatonshipdegree / relationshipdegree * 100;
只看计算顺序。您想将 19 除以 35。所以它是 0。然后将 0 和 100 相乘。它也是 0。
所以您可以尝试通过类型转换使该表达式的第一个变量浮动:
float percentrelation = (float)Individualrelatonshipdegree / relationshipdegree * 100;
UPD需要解释类型转换的时刻。计算顺序是从左到右。我们有一个规则,在使用整数(int、byte、long long 等)和 float(float、double 等)操作数时,它们都被强制转换为浮点类型。这就是为什么我们只需要在第一个操作数上进行一次类型转换。这就是为什么 1.0f * 的另一个答案your expression
也可以正常工作的原因。只是两种不同的方式。
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.