我的 Java 类(class)有一个问题需要解决,但由于我是这门语言的新手,我似乎找不到解决方案。如果有人能帮助我解决这个问题,我会很高兴。
问题是 H
应该定义为 double
,因为它可能包含像 2.5
这样的十进制值。
当前代码可以完美运行,但仅适用于 H
的整数。我尝试使用 double H = 2.5;
但随后一切都变得一团糟。另外,我读到了从 int 到 double 的开关,反之亦然,尝试了一些代码,但如果我使用 switch,它会破坏 P1 * H
和 P2 * H
。
public class PoolTask {
public static void main(String[] args) {
int V = 200;
int P1 = 150;
int P2 = 170;
int H = 2;
int P1w = P1 * H;
int P2w = P2 * H;
int Pt = P1w + P2w;
if (Pt <= V) {
int percentage1 = (Pt * 100 / V);
int percentage2 = (P1w * 100 / Pt);
int percentage3 = (P2w * 100 / Pt);
System.out.println("The pool is " + percentage1 + "% full. Pipe 1: " + percentage2 + "%. Pipe 2: " + percentage3 + "%.");
} else if (Pt > V) {
int liters = (Pt - V);
System.out.println("For " + H + " hours the pool overflows with " + liters + " liters");
} else {
System.out.println("");
}
}
}
最佳答案
这都是因为您仅为 H 指定了double
数据类型。
在使用其他值进行计算后,当您将结果保存到 int
类型的变量中时,结果会丢失其小数部分,因为您无法将其保存为 int
类型的变量
声明所有 double
类型的变量,以摆脱您面临的困惑
关于java - 定义变量并使用开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41706213/