处理int型而不是double型的Java方法



当我使用142.14调用该方法时,我没有得到任何错误,但是控制台根本没有打印任何内容。当我发送142时,它按预期工作。为什么会这样?这个代码是在Java中,我需要添加更多的细节来问这个问题,所以在这里我添加更多的细节。

public class Testing {
static int twentyCount = 0;
static int tenCount = 0;
static int fiveCount = 0;
static int dollarCount = 0;
static int quarterCount = 0;
static int dimeCount = 0;
static int nickelCount = 0;
static int pennyCount = 0;

public static void main(String[] args) {

returnChange(142.14);
}

public static void returnChange(double change) {


while (change >= 1.0) {
if(change >= 20.0) {
change = change - 20.0;
twentyCount++;
continue;
} if(change >= 10.0) {
change = change - 10.0;
tenCount++;
continue;
} if(change >= 5.0) {
change = change - 5.0;
fiveCount++;
continue;
} if(change >= 1.0) {
change = change - 1.0;
dollarCount++;
continue;
}
}
while (change != 0.0) {
if(change >= .25) {
change = change - .25;
quarterCount++;
continue;
} if(change >= .1) {
change = change - .1;
dimeCount++;
continue;
} if(change >= .05) {
change = change - .05;
nickelCount++;
continue;
} if(change >= .01) {
change = change - .01;
pennyCount++;
continue;
}
}
System.out.println("Change dispensed:  " + twentyCount + " 20's, " + tenCount + " 10's, " + fiveCount + " 5's, "
+ dollarCount + " 1's, " + quarterCount + " quarters, " + dimeCount + " dimes, "
+ nickelCount + " nickels, and " + pennyCount + " pennies.");
}

}

考虑一下。更改可能是0.009999,因此不会被任何条件更新。它也不等于0.0。所以它会永远运行下去。在本例中,输入:

while (change >= .01) // the smallest value you care about.
...
...
...
} if(change >= .01) {
change = change - .01;
pennyCount++;
continue;
}
}

它仍然会更新美分并正确退出。在将来的情况下,要么用分来表示你的钱(例如143.14 is 14314 cents),要么用BigDecimal来计算。一般来说,不要使用双精度值表示货币。

最新更新