简体   繁体   English

我的Java代码有什么问题?

[英]What is wrong in my java code?

I have to do a little calculating but something is not working well, can anybody tell what? 我需要做一些计算,但是有些事情做得不好,有人可以告诉我什么吗?

For example if i have one false and one true, it should be 50% but it gives me 0%, what is wrong here? 例如,如果我有一个错误和一个真实的,则应为50%,但给我0%,这是怎么回事?

for (Verhuur verhuur : verhuur)
{
    if(verhuur.getSchade() == true)
    {
        welSchade = welSchade + 1;
    }
    if(verhuur.getSchade() == false)
    {
        geenSchade = geenSchade + 1;
    }
}
percentageSchade = (welSchade / (welSchade + geenSchade)) * 100;
System.out.println("Het percentage boten met schade is " + percentageSchade + " %." );

您可能要将其转换为两倍:

((double)welSchade / (welSchade + geenSchade)) * 100

Your problem is that you are dividing an integer by a larger integer, which returns 0, since integers don't have fractions. 您的问题是您将一个整数除以一个较大的整数,该整数返回0,因为整数没有小数。

You can either change the order of operations (multiply by 100 before the division, to ensure the result of the division is at least 1) or work with double or float variables, which would allow results between 0 and 1. 您可以更改操作顺序(除法前乘以100,以确保除法的结果至少为1),也可以使用doublefloat变量,这将使结果介于0到1之间。

If welSchade and geenSchade are integers, then, the result of their division will be an integer. 如果welSchadegeenSchade是整数,则它们的除法结果将是整数。 Thus, 0.5 would be evaluated to 0, which is why you are getting 0. 因此,将0.5评估为0,这就是为什么得到0的原因。

The problem is in the first line: 问题在第一行:

for (Verhuur verhuur : verhuur)

The second verhuur should be the variable name to iterate on. 第二个verhuur应该是要迭代的变量名。 So probably something like this: 所以大概是这样的:

for (Verhuur verhuur : verhuurItems)

EDIT: 编辑:

Like the other answers are suggesting, you also have to make floats from the integers or evaluate the expression as a float, like this: 就像其他答案所暗示的那样,您还必须从整数中生成浮点数或将表达式评估为浮点数,如下所示:

((float)welSchade/((float)geenSchade+welSchade))*100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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