【问题标题】:dividing a number into other significant digits将一个数字分成其他有效数字
【发布时间】:2013-10-05 15:33:19
【问题描述】:

标题很混乱,因为我不知道该问题的标题是什么。无论如何,我有 java 编程作业,需要将一个数字分成正确的变化量。使用程序时没有收到任何消息,我可以输入数字,然后没有任何反应。

谢谢

-乔丹

double input;   // The input
double l = 0;   // Toonies (2.00 dollars)
double t = 0;   // loonies (1.00 dollars)
double q = 0;   // quarters (0.25 dollars)
double d = 0;   // dimes (0.10 dollars)
double n = 0;   // nickels (0.05 dollars)
double p = 0;   // pennies (0.01 dollars)

System.out.println("Hello, this application will tell you how much"
        + "change you have, based on your input.");
System.out.println("Please enter a real integer");
input = TextIO.getDouble();     // Retrieves the next double entered

while (input > 2) {
    t++;
} // Closes of toonie statement

while (input > 1) {
    l++;
} // Closes of loonie statement

while (input > 0.25) {
    q++;
} // Closes of quarter statement

while (input > 0.1) {
    d++;
} // Closes of dime statement

while (input > 0.05) {
    n++;
} // Closes of nickel statement

while (input > 0.01) {
    p++;
} // Closes of penny statement

System.out.println("You have "  // Prints a message saying how many of each coin you have
        + t + "toonies, "
+ l + "loonie(s), "
+ q + "quarter(s), "
+ d + "toonie(s), "
+ n + "toonies(s), "
+ p + "pennies(s), ");

【问题讨论】:

  • 都可能是无限循环。
  • 如果输入大于任何 while 循环要求,它将进入无限循环,您需要根据增加的变化量减少输入。
  • 旁注,你应该看看System.out.printf

标签: java currency


【解决方案1】:

在每个 while 循环中,您还需要从输入中减去数量。既然你不是,它可能会在其中一个上进入无限循环。例如:

while (input > 2) {
    t++;
    input -= 2;
}

【讨论】:

    【解决方案2】:

    您没有减少输入,因此您在初始条件为真的第一个 while 中陷入无限循环:

    您应该减少循环中的 input 数量:

    while (input > 2) {
        t++;
        input -=2;
    }
    

    【讨论】:

      【解决方案3】:

      变量 'input' 永远不会减少,因此一旦进入其中一个 while 循环,就无法退出它,它会一直持续到您通过其他方式停止程序为止。

      【讨论】:

        【解决方案4】:

        我建议你用美分计算。这样就可以长期使用了。您可以只使用整数除法,而不是使用循环。这将更快、更短、更准确。

        【讨论】:

          猜你喜欢
          • 2020-05-16
          • 2020-02-09
          • 1970-01-01
          • 1970-01-01
          • 2012-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多