我正在创建一个程序,它打印从0到用户输入数字的偶数之和。例如,如果用户输入数字20,程序将计算0到20之间所有偶数的总和。
当我使用数字10测试程序时,它有效。但我尝试使用不同的数字,35,它只是陷入无限循环。我将不胜感激任何帮助。代码将发布在下面:
(编辑)感谢大家的反馈!在与朋友交谈后,我们意识到解决方案实际上非常简单。我们只是让它变得复杂。不过,感谢所有的建议。
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// @me
// @version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
答案 0 :(得分:1)
为什么要为此编写循环,有效的方法。
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
其中N =用户给定的输入数,您希望添加偶数
注意:您可以在输入数字上添加验证,即使是(n%2 == 0),如果不是
则返回错误答案 1 :(得分:0)
你在条件中使用的变量(即 sum &amp; user_num )在奇数的情况下没有人改变,你的代码卡在永无止境的循环中。 您应该使用计数器变量(例如 i 从1到user_num)并在条件中使用该数字。例如:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
答案 2 :(得分:0)
你的for循环应该是这样的。
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
你的初始程序只是检查输入的数字是偶数还是奇数。 和输入的数字相加。 因此总和是输入数字的两倍是偶数。 如果输入的数字是奇数,它将进入无限循环,因为entered_num(奇数)%2 == 0总是为false并执行else语句。