如何总结while循环中的结果而centain输入将结束while循环? [英] How to sum up the resultes in a while loop while centain input will end the while loop?
本文介绍了如何总结while循环中的结果而centain输入将结束while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在java中有一个情况;
I have a situation in java;
我想请用户输入一些数字&总共有这些数字.但是,如果用户输入负数,它将结束循环;
I would like to ask the user to put in some numbers & have a total of those numbers. However if the user enter a negative number it will end the loop;
目前我有一个如下所示的while循环;
currently I have a while loop as below;
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.
However it does not do the job. If the user put in 40,60,50, and -1 the correct result should be 150; my loop result in 109.
请帮忙!
非常感谢!杰基
推荐答案
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();
}
我建议变量名不要以大写字母开头.
I recommend variable names not to start with upper case letters.
这篇关于如何总结while循环中的结果而centain输入将结束while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文