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

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

问题描述

我的目标:编写一个应用程序,使用 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++;

推荐答案

使用公共变量来存储 sum

use a common variable to store sum

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天全站免登陆