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

时间:2019-02-27 06:56:21

标签: java percentage

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

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

3 个答案:

答案 0 :(得分:0)

因为收益是整数,成本也是整数,收益/成本将返回整数,并且如果收益小于成本,则收益/成本= 0。使表达式变为float / int,将返回float

答案 1 :(得分:0)

这是因为您正在对int进行除法,从而得到zero。因此,您需要先将gaincost强制转换为浮点数,然后再乘以100。 例如: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");
    }

}

}

答案 2 :(得分:0)

使用gp=(((float)gain/(float)cost)*100)并将if(op != 0 && rc != 0 && sp != 0)替换为if(op > 0 && rc >= 0 && sp > 0)