创建运输和折扣计算器获取错误的数字

时间:2018-01-20 15:52:32

标签: java

我正在尝试创建一个程序,提示用户输入他正在购买的衬衫数量,并根据他的订单确定应用的折扣和运费。我尝试了两种不同的方法,如第一个if语句中所示,然后是其他方法。当我用1件衬衫测试时,我得到的总数为29,无论出于什么原因它都会乘以29倍而不是24.5并且不会增加10件或更少的运费。

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);

        System.out.print("Please enter the number of shirts ordered:");
        int shirts = input.nextInt();
        int cost = 0;
        float shirt = 24.95f;

        if (shirts <=2) {
            cost = (int) (shirt * cost );
        }
        if (shirts <=5)
            cost = (int) (shirts*24.95f + 8.00f);   
        {
        if (shirts <=10)
            cost = (int) (shirts*24.95f + 5.00f);   

        if (shirts >=11)
            cost = (int) (shirts*24.95f);   

        System.out.print(cost);



        }
    }
}

3 个答案:

答案 0 :(得分:0)

你的cost变量是int,当它应该像float一样,不要把结果转换为你的代码中的int remove(int)

答案 1 :(得分:0)

每当输入为1时,它将进入以下条件并将值返回为29,这是预期的。 (INT)(1 * 24.95f + 5.00f)= 29 if(衬衫&lt; = 10)         cost =(int)(衬衫* 24.95f + 5.00f);
这就是为什么它总是让你退缩29。

请更改条件,尝试使用类似的独特条件 if(shirts = 1)等等,以便正确的值作为输出。

希望这会对你有所帮助。如果您有任何疑问,可以联系我。

谢谢, Raghava

答案 2 :(得分:0)

您的计划的主要问题是缺少else-if声明。

public static void main(String[] args) {

    Scanner input = new Scanner (System.in);

    System.out.print("Please enter the number of shirts ordered:");
    int shirts = input.nextInt();
    int cost = 0;
    float shirt = 24.95f;

    if (shirts <=2) 
        cost = (int) (shirt * cost );

    else if (shirts <=5)
        cost = (int) (shirts*24.95f + 8.00f);   

    else if (shirts <=10)
        cost = (int) (shirts*24.95f + 5.00f);   

    else if (shirts >=11)
        cost = (int) (shirts*24.95f);   

    System.out.print(cost);

}

另一个问题是使用Integer,如果您使用定价系统,最好使用浮点数或双精度数,因此将变量成本更改为double cost = 0;,这样就可以避免转换所有这些浮动计算到int

您还可以检查用户是否输入了一个号码,他可能会意外输入charString

在您的代码中,您获得29的原因是您将费用用作Int,所以:

  1. 如果 1 是输入,那么1 <= 2 = True 但是,因为你没有else-if它继续检查所有其他if True 1}}陈述。
  2. 这样,返回(int) (shirts*24.95f + 5.00f)的最后一个是第三个,使您的费用变量等于(int) (shirts*24.95f + 5.00f)
  3. (int) (24.95f + 5.00f) - &gt; (int) (29.95f ) - &gt; 29 - &gt; man sbrk