如何在 Java 中写出五的总和
How to Write a Summation of Fives in Java
我需要在 Java 中编写一个程序,可以将 5 的倍数与用户给定的值相加,然后将所有倍数相加。我需要用一个while循环来写它。
这是我目前的情况:
import java.util.Scanner;
public class SummationOfFives {
public static void main(String[] args){
//variables
double limit;
int fives = 0;
//Scanner
System.out.println("Please input a positive integer as the end value: ");
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
limit = input.nextDouble();
//While Loop
while ((fives+5)<=limit)
{
fives = fives+5;
System.out.println("The summation is: "+fives);
}
}
}
然而,当我 运行 这个程序时,它给我的只是倍数:
Please input a positive integer as the end value:
11
The summation is: 5
The summation is: 10
我在你的循环中添加了一个 total 变量,它将累加所有求和的值。
int counter =1;
int total = 0;
//While Loop
while ((fives+5)<=limit)
{
total = counter*5;
counter++;
fives = fives+5;
System.out.println("The summation is: "+fives);
System.out.println("The total is: "+total);
}
你快到了!想想你的输出告诉你什么。在您的 while
循环中,fives
是每次迭代中下一个 5 的倍数。您不会将它添加到任何地方的总变量中。
因此 - 在循环之前定义总计,例如
int total = 0;
继续在循环中添加它(你的 System.out.println
现在所在的位置)例如
total = total + fives;
输出循环后的总数例如
System.out.println(total);
你在fives
中做的求和是错误的。您需要另一个初始化为 0
的变量 multiple
,您将在循环的每一步递增 5。 while
中的停止条件为(multiple < limit)
。那么fives
就是multiple
的总和。
double limit;
int fives = 0;
int multiple = 0
//While Loop
while (multiple<=limit)
{
multiple += 5;
fives = fives + multiple;
System.out.println("So far, the summation is: "+fives);
}
我需要在 Java 中编写一个程序,可以将 5 的倍数与用户给定的值相加,然后将所有倍数相加。我需要用一个while循环来写它。
这是我目前的情况:
import java.util.Scanner;
public class SummationOfFives {
public static void main(String[] args){
//variables
double limit;
int fives = 0;
//Scanner
System.out.println("Please input a positive integer as the end value: ");
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
limit = input.nextDouble();
//While Loop
while ((fives+5)<=limit)
{
fives = fives+5;
System.out.println("The summation is: "+fives);
}
}
}
然而,当我 运行 这个程序时,它给我的只是倍数:
Please input a positive integer as the end value:
11
The summation is: 5
The summation is: 10
我在你的循环中添加了一个 total 变量,它将累加所有求和的值。
int counter =1;
int total = 0;
//While Loop
while ((fives+5)<=limit)
{
total = counter*5;
counter++;
fives = fives+5;
System.out.println("The summation is: "+fives);
System.out.println("The total is: "+total);
}
你快到了!想想你的输出告诉你什么。在您的 while
循环中,fives
是每次迭代中下一个 5 的倍数。您不会将它添加到任何地方的总变量中。
因此 - 在循环之前定义总计,例如
int total = 0;
继续在循环中添加它(你的 System.out.println
现在所在的位置)例如
total = total + fives;
输出循环后的总数例如
System.out.println(total);
你在fives
中做的求和是错误的。您需要另一个初始化为 0
的变量 multiple
,您将在循环的每一步递增 5。 while
中的停止条件为(multiple < limit)
。那么fives
就是multiple
的总和。
double limit;
int fives = 0;
int multiple = 0
//While Loop
while (multiple<=limit)
{
multiple += 5;
fives = fives + multiple;
System.out.println("So far, the summation is: "+fives);
}