如何计算java中的增益百分比?什么是

问题描述 投票:-1回答:2

我运行此代码时输出错误*****

package gain_per;
import java.util.Scanner;

public class Gain {

    public static void main(String[] args) {

        Scanner sn = new Scanner(System.in);
        int op,rc,sp,cost,gain;
        double gp=0;

        System.out.println("Enter Old Price:");
        op = sn.nextInt();

        System.out.println("Enter Repair cost:");
        rc = sn.nextInt();

        System.out.println("Enter Selling Price:");
        sp = sn.nextInt();

        if(op != 0 && rc != 0 && sp != 0) {

            cost = op+rc;

            if(cost<sp) {

                gain = sp-cost;
                gp = (float)((gain / cost) * 100);

                System.out.println(gp);

            }
            else {

                System.out.println("Cannot Calculate");
            }

        }
        else {

            System.out.println("Invalid Input");
        }

    }

}

这是我的代码!!!这有什么问题?我得到的输出是0.0

java percentage
2个回答
0
投票

因为增益是int,成本也是int,增益/成本将返回int,如果增益低于成本则增益/成本= 0.你需要施放如:((浮动)增益)/成本,来表达变为float / int,将返回float


0
投票

这是因为你正在对int进行划分,这将给zero。所以你需要做的是首先将gaincost浮动然后乘以它,例如:gp = (((float) gain / (float) cost) * 100);

完整代码:

package gain_per;
import java.util.Scanner;

public class Gain {

public static void main(String[] args) {

    Scanner sn = new Scanner(System.in);
    int op,rc,sp,cost,gain;
    double gp=0;

    System.out.println("Enter Old Price:");
    op = sn.nextInt();

    System.out.println("Enter Repair cost:");
    rc = sn.nextInt();

    System.out.println("Enter Selling Price:");
    sp = sn.nextInt();

    if(op != 0 && rc != 0 && sp != 0) {

        cost = op+rc;

        if(cost<sp) {

            gain = sp-cost;
            gp = (((float) gain / (float) cost) * 100);

            System.out.println(gp);

        }
        else {

            System.out.println("Cannot Calculate");
        }

    }
    else {

        System.out.println("Invalid Input");
    }

}

}
© www.soinside.com 2019 - 2024. All rights reserved.