使用循环求和 [英] Sum numbers using loop

查看:65
本文介绍了使用循环求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标:编写一个使用while循环从用户那里获取20个输入并显示所有这些数字之和的应用程序.

My objective: write an application that uses while loop to get 20 inputs from a user and displays the sum of all those numbers.

我知道如何进行while循环,但是我不知道如何得到所有这些数字的和(因为变量将是相同的).这是我到目前为止的内容:

I get how to do the while loop but I don't know how to get the sum of all those numbers (because the variable will be the same). Here is what I have so far:

Scanner Numb = new Scanner (System.in); 
int count = 0;
while (count<20) {
    System.out.println("Enter number: ");
    int numb = Numb.nextInt();
    count++;

推荐答案

使用公共变量存储总和

int sum = 0;
int count = 0;
while (count<20) {
    System.out.println("Enter number: ");
    int numb = Numb.nextInt();
    sum = sum+numb;
    count++;
}
System.out.println("sum is "+sum);

这篇关于使用循环求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆