我是Java新手,我现在正在学习。我想创建一个小程序,可以总结我在程序中显示的所有数字。我的程序的主要思想要求我提供许多数字。这是循环:
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
}
我想知道我的程序如何总结我所有的数字?
我是Java新手,我现在正在学习。我想创建一个小程序,可以总结我在程序中显示的所有数字。我的程序的主要思想要求我提供许多数字。这是循环:
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
}
我想知道我的程序如何总结我所有的数字?
您需要声明一个变量来保存总和:
int f, sum = 0;
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
sum += f;
}
Try this
int answer = 0;
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
answer += f;
}
System.out.println(answer);
// assuming userInput is a Scanner
int sum = 0;
int f;
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
sum += f;
}
// sum now holds the sum of all numbers
Assuming you did create a scanner
object before this segment of code you can simply have a sum
variable that hold the sum of your inputs.
int sum =0;
for (int k = 1; k <= 6 ; k++){
System.out.println("Type " + k +". number");
f = userInput.nextInt();
sum += f;
}
您需要使用另一个变量来存储总和。
int sum = 0;
for (int k = 1; k <= 6; k++) {
System.out.println("Type " + k +". number");
f = userInput.nextInt();
sum = sum + f;
}