【问题标题】:How to sum up the resultes in a while loop while centain input will end the while loop?当某些输入将结束while循环时,如何总结while循环中的结果?
【发布时间】:2013-01-06 00:53:42
【问题描述】:

我在java中有一个情况;

我想请用户输入一些数字并获得这些数字的总和。但是,如果用户输入负数,它将结束循环;

目前我有一个如下的while循环;

                double sum = 0;
    double Input = 0;
    System.out.println("Please enter the numbers (negative to end)")
    System.out.println("Enter a number");
    Scanner kdb = new Scanner(System.in);
          Input = kdb.nextDouble();
    while (Input > 0)
    {
        System.out.println("Enter an income");
        Input = kdb.nextDouble();
        sum = Input;
    }

但是它并没有完成这项工作。如果用户输入 40、60、50 和 -1 正确的结果应该是 150;我的循环结果为 109。

请帮忙!

非常感谢! 杰基

【问题讨论】:

  • 您至少有 2 个问题。 #1 - 非常仔细地查看您的代码,并告诉我们在输入负数时会发生什么——确切地说。 #2 - 向我们解释这是如何求和的。

标签: java while-loop sum


【解决方案1】:
double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
    sum += Input;
    System.out.println("Enter an income");
    Input = kdb.nextDouble();
}

我建议变量名不要以大写字母开头。

【讨论】:

  • 我还会建议使用do-while 来执行此操作。
  • 我们或许应该教他们钓鱼,而不是给他们鱼。
  • @TonyEnnis 我同意你的看法。这些是一些非常简单的基础知识,应该研究一下。
  • @user1952050:希望你不要简单的拿代码,还要想想你的代码有什么不同。
  • @MrSmith42 这是一个学习过程。我太愚蠢了,在你提醒我应该总结之前尝试了 3 个小时,然后再要求另一个数字!再次感谢您!
【解决方案2】:

您应该在 sum += Input 之前检查 Input > 0。

【讨论】:

    【解决方案3】:

    这应该可行!

            double sum = 0;
        double Input = 0;
        boolean Adding= true;
        System.out.println("Please enter the numbers (negative to end)");
    
        Scanner kdb = new Scanner(System.in);
        while(Adding == true)
        {
            System.out.print("Enter a number: ");
            Input = kdb.nextDouble();
            if(Input > 0)
            {
                sum+= Input;
            }
            else
                Adding = false;
    
        }
        System.out.println("Your sum is: " + sum);
    

    【讨论】:

    • (Adding == true)(Adding) 有什么问题?此外,为什么你的变量名以大写字母开头?
    • MrSmith 下面的代码更好。更少的逻辑更少的代码相同的结果。
    • 不确定这是否有效,哈哈,懒得检查。我现在只使用(添加)。
    【解决方案4】:

    第一个输入值被第二个输入值覆盖,因为总和仅在循环结束时完成。

    **double sum = 0;
    double Input = 0;
    System.out.println("Please enter the numbers (negative to end)");
    System.out.println("Enter a number");
    Scanner kdb = new Scanner(System.in);
          Input = kdb.nextDouble();
    while (Input>0)
    {
        sum+= Input;
        System.out.println("Enter an income");
        Input = kdb.nextDouble();
    
    }
    System.out.println(sum);
    }**
    

    输出是:

    Please enter the numbers (negative to end)
    

    输入一个数字 40 输入收入 50 输入收入 60 输入收入 -1 150.0

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 2019-03-19
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 2019-03-15
      • 2016-02-08
      相关资源
      最近更新 更多