【问题标题】:Shipping Charges Calculator miss calculation运费计算器错过计算
【发布时间】:2016-02-27 02:20:19
【问题描述】:

作业的费率如下: 每 500 英里装运的包裹重量 2 磅或更少 $1.10 超过 2 磅但不超过 6 磅 $2.20 超过 6 磅但不超过 10 磅 $3.70 超过 10 英镑 $3.80

每 500 英里的运费不按比例计算。例如,如果一个 2 磅的包裹运送 502 英里,则费用为 2.20 美元。编写一个程序,要求用户输入包裹的重量,然后显示运费。

我的问题是我得到了错误的答案。这是我到目前为止得到的:

import java.util.Scanner;
public class ShippingCharges
{
public static void main (String [] args)
{
    double mDrive, rMiles, wPound;

    Scanner keyboard = new Scanner (System.in);

    System.out.print ("Enter Weight of Package: ");
    wPound = keyboard.nextDouble();
    System.out.println("");

    System.out.print ("Enter Miles Driven: ");
    mDrive = keyboard.nextDouble();
    System.out.println("");

    rMiles = mDrive / 500;

    if (wPound <2)
    {
        System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*1.10);
    }

    if (wPound >=2 && wPound <6)
    {
        System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*2.20);
    }

    if (wPound >=6 && wPound <10)
    {
        System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*3.70);
    }

    if (wPound >= 10)
    {
        System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*3.80);
    }

}
}

按照示例,程序应该执行 502/500 *2.2 即 2.2 并且程序显示 4.4。有什么建议吗?

【问题讨论】:

  • 根据提供的说明,您的代码应为if(wPound&lt;=2)if(wPound&gt;2 &amp;&amp; wPound&lt;=6) 等。顺便说一句,您可以使用if(wPound&lt;=2)else if(wPound&lt;=6) 等等。
  • 哈罗德:它有效。我应该对另一个或只是这个做同样的事情吗?卡尔文:仍然给出相同的答案
  • @JonathanSGutierrez 阅读 Calvins 的回答。他是对的。如果您修复 if 语句,它应该可以工作。保持 Math.ceil 不变并尝试一下。
  • @Harold 我的错,我放错了地方,但适用于示例。

标签: java if-statement java.util.scanner


【解决方案1】:

你的 if 语句是罪魁祸首。按照您提供的说明,声明应如下所示

if (wPound<=2) {
    System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*1.10);
}
else if(wPound<=6) {
    System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*2.20);
}
else if (wPound<=10) {
    System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*3.70);
}
else {
    System.out.println ("You will be charged "+ "$" + Math.ceil(rMiles)*3.80);
}

【讨论】:

  • 1 最后一个问题:如果 wPound = 5 的值,第 2 和第 3 语句不应该为真吗?
  • 是的,但是使用else if,它将落入第一个评估为真的语句并跳过其余的@JonathanSGutierrez
  • 感谢您所做的一切!我对那部分有点困惑。
猜你喜欢
  • 1970-01-01
  • 2010-11-28
  • 2014-08-04
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多