定义变量和使用开关

时间:2017-01-17 20:19:47

标签: java variables

我有一个问题需要解决我的Java课程,但由于我是这门语言的新手,我似乎无法找到解决方案。如果有人可以帮助我,我会很高兴。

问题是H应定义为double,因为它可能包含2.5之类的小数值。

当前代码完美无缺,但仅适用于H的整数。我尝试了double H = 2.5;,但后来所有人都搞砸了。另外,我读到了从int到double的swithes,反之亦然,尝试了一些代码,但如果我使用switch,它会破坏P1 * HP2 * 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("");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这都是因为您只为H指定了double数据类型。 当您将结果保存到int类型的变量中时,使用其他值进行计算后,结果会丢失其小数部分,因为您无法为int类型的变量保留该结果

声明所有类型为double的变量,以摆脱您所面临的混乱

答案 1 :(得分:1)

您可以将所有变量转换为double,如下所示:

class PoolTask {
    public static void main(String[] args) {
        double V = 200;
        double P1 = 150;
        double P2 = 170;
        double H = 2.0;

        double P1w = P1 * H;
        double P2w = P2 * H;
        double Pt = P1w + P2w;

        if(Pt <= V) {
            double percentage1 = (Pt * 100 / V);
            double percentage2 = (P1w * 100 / Pt);
            double percentage3 = (P2w * 100 / Pt);
            System.out.println("The pool is " + percentage1 + "% full. Pipe 1: " + percentage2 + "%. Pipe 2: " + percentage3 + "%.");             
        } else if (Pt > V) {
            double liters = (Pt - V);
            System.out.println("For " + H + " hours the pool overflows with " + liters + " liters");
        } else {
            System.out.println("");
        }
    }
}

但是,如果您不希望显示带有小数值的变量(例如percentage1),则可以在print语句中将其强制转换为int

System.out.println("The pool is " + (int)percentage1 + ...)