如何使用循环求偶数之和

huangapple go评论69阅读模式
英文:

How To Sum The Even Numbers Using Loop

问题

我在这段代码中遇到了问题涉及到对偶数进行求和我希望的情况是偶数将被输出同时还会有一个输出在用户输入的范围内对所有偶数进行求和我只是一个编程初学者希望一些人能帮助我

import java.util.*;

public class Loop {
    //开始
    public static void main(String args[]) {
        
        Scanner console = new Scanner(System.in);
        System.out.println("输入起始数字");
        int start = console.nextInt();
        System.out.println("输入结束数字");
        int end = console.nextInt();
        
        int sum = 0;
        System.out.println("在" + start + "和" + end + "之间的偶数是:");
        for (int r = start; r <= end; r++) {
            //如果数字%2 == 0,则表示它是一个偶数
            if(r % 2 == 0) {
                System.out.println(r);
                sum += r;  // 对偶数进行求和
            }
        }
        
        System.out.println("在输入范围内的偶数之和为:" + sum);
    }
}
英文:

I need help on this code I seem to have a problem regarding on summing the even numbers, what I want to happen is that the even numbers will be outputted and at the same time there will be an output where all the even numbers are summed within the inputted range of the user. I am just a beginner at coding and I hope some people can help me.

import java.util.*;
public class Loop
{
    //Start
    public static void main(String args[]) 
    {
        
        Scanner console = new Scanner(System.in) ;
        System.out.println(&quot;Enter Start Number&quot;) ;
        int start =console.nextInt();
        System.out.println(&quot;Enter End Number&quot;) ;
        int end =console.nextInt();
        
        int sum = 0;
        System.out.println(&quot;The even numbers between &quot;+start+&quot; and &quot;+end+&quot; are the following: &quot;);
        for (int r = start; r &lt;= end; r++)
        {
        //if number%2 == 0 it means its an even number
        if(r % 2 == 0)
        {
        System.out.println(r);
        }
        }
    }
}

答案1

得分: 2

用Java流的简洁方法。只是在这里放着让你知道还有另一种方法可以这样做:

int sum = IntStream.range(start, 1 + end).filter(num -> 0 == num % 2).peek(System.out::println).sum();
System.out.println(sum);
英文:

A concise way using Java streams. Just putting it here so that you know that there is another way to do this:

int sum = IntStream.range(start, 1 + end).filter(num -&gt; 0 == num % 2).peek(System.out::println).sum();
System.out.println(sum);

答案2

得分: 1

你可以使用 sum+=r; 并获得和:

public static void main(String args[])
{
    Scanner console = new Scanner(System.in);
    System.out.println("输入起始数字");
    int start = console.nextInt();
    System.out.println("输入结束数字");
    int end = console.nextInt();

    int sum = 0;
    System.out.println("在 " + start + " 和 " + end + " 之间的偶数有以下:");
    for (int r = start; r <= end; r++)
    {
        // 如果数字%2 == 0,则是偶数
        if(r % 2 == 0)
        {
            sum += r;
            System.out.println(r);
        }
    }
    System.out.println("在 " + start + " - " + end + " 之间偶数的和为:" + sum);
}

输出:

输入起始数字
10
输入结束数字
20
在 10 和 20 之间的偶数有以下:
10
12
14
16
18
20
在 10 - 20 之间偶数的和为:90
英文:

You can use with sum+=r; and get the sum :

	public static void main(String args[]) 
    {
        
        Scanner console = new Scanner(System.in) ;
        System.out.println(&quot;Enter Start Number&quot;) ;
        int start =console.nextInt();
        System.out.println(&quot;Enter End Number&quot;) ;
        int end =console.nextInt();
        
        int sum = 0;
        System.out.println(&quot;The even numbers between &quot;+start+&quot; and &quot;+end+&quot; are the following: &quot;);
        for (int r = start; r &lt;= end; r++)
        {
        //if number%2 == 0 it means its an even number
        if(r % 2 == 0)
        {
        	sum += r;
        System.out.println(r);
        }
        }
        System.out.println(&quot;The sum of even numbers between :&quot;+start +&quot; - &quot;+end +&quot; is : &quot;+sum);
    }
}

Output :

Enter Start Number
10
Enter End Number
20
The even numbers between 10 and 20 are the following: 
10
12
14
16
18
20
The sum of even numbers between :10 - 20 is : 90

答案3

得分: 1

你离成功很近了

   int sum = 0;
    System.out.println("在" + start + "和" + end + "之间的偶数如下:");
    for (int r = start; r <= end; r++)
    {
    if(r % 2 == 0)
    {
    sum = sum + r;
    System.out.println(r);
    }
    }
    System.out.println("总和:" + sum);
英文:

you are almost there

   int sum = 0;
    System.out.println(&quot;The even numbers between &quot;+start+&quot; and &quot;+end+&quot; are the following: &quot;);
    for (int r = start; r &lt;= end; r++)
    {
    if(r % 2 == 0)
    {
    sum = sum + r;
    System.out.println(r);
    }
    }
    System.out.println(&quot;the sum : &quot;+sum);

答案4

得分: 1

当您打印一个偶数时,在循环内同时将其添加到 sum,并在循环结束后打印 sum 的值。

for (int r = start; r <= end; r++) {
    // 如果数字模2等于0,则表示为偶数
    if (r % 2 == 0) {
        System.out.println(r);
        sum += r;
    }
}

System.out.println("Sum = " + sum);
英文:

When you print an even number, also add it to sum and print the value of sum after the loop.

for (int r = start; r &lt;= end; r++) {
	//if number%2 == 0 it means its an even number
	if(r % 2 == 0) {
		System.out.println(r);
		sum += r;
	}
}

System.out.println(&quot;Sum = &quot; + sum);

答案5

得分: 1

我不明白为什么要将 r 增加1,而不是这样做:

if (r % 2 == 1)  // 如果 `r` 是奇数
    r++;

for (; r <= end; r += 2) {
    System.out.println(r);
    sum += r;
}

System.out.println("Sum = " + sum);
英文:

I do not understand why are you incrementing r by one, instead do this:

if (r % 2 == 1)  // if `r` is odd
    r++;

for (; r &lt;= end; r+=2) {
    System.out.println(r);
    sum += r;
}

System.out.println(&quot;Sum = &quot; + sum);

</details>



# 答案6
**得分**: 1

以下是翻译好的内容:

你可以大大简化!
通过创建临时变量 `t`

1. 如果 `start` 是奇数,初始化 `t = start + 1`,否则 `t = start`
2. 使用一个公式计算两个数字之间的 `sum`
3. 另外,将循环变量增加 `2`,而不是 `1`
```java
public static void main(String args[]) {
    Scanner console = new Scanner(System.in);
    System.out.println("输入起始数字");
    int start = console.nextInt();
    System.out.println("输入结束数字");
    int end = console.nextInt();
    System.out.println("在 " + start + " 和 " + end + " 之间的偶数有以下:");

    int t = start % 2 == 1 ? start + 1: start;
    int sum = ((t + end) / 2) * ((end - t + 2) / 2);

    while(t <= end) {
        System.out.println(t);
        t += 2;
    }
    
    System.out.println("在 " + start + " 到 " + end + " 之间偶数的和为:" + sum);
}

注意:如果我们使用位运算符,我们可以用以下方式替代:

  1. int t = start % 2 == 1 ? start + 1: start;int t = start + (start & 1); 替代

  2. int sum = ((t + end) / 2) * ((end - t + 2) / 2);int sum = ((t + end) >> 1) * ((end - t + 2) >> 1); 替代

最终解决方案

public static void main(String args[]) {
    Scanner console = new Scanner(System.in);
    System.out.println("输入起始数字");
    int start = console.nextInt();
    System.out.println("输入结束数字");
    int end = console.nextInt();
    System.out.println("在 " + start + " 和 " + end + " 之间的偶数有以下:");

    int t = start + (start & 1);
    int sum = ((t + end) >> 1) * ((end - t + 2) >> 1);
    while(t <= end) {
        System.out.println(t);
        t += 2;
    }
    System.out.println("在 " + start + " 到 " + end + " 之间偶数的和为:" + sum);
}
英文:

You can simplify by a lot!
By creating a temporary variable t

  1. If start is odd, initialise t = start + 1, otherwise t = start
  2. Use a formula to calculate sum between two numbers
  3. Also, increment the loop variable by 2 instead of 1
public static void main(String args[]) {
    Scanner console = new Scanner(System.in);
    System.out.println(&quot;Enter Start Number&quot;);
    int start = console.nextInt();
    System.out.println(&quot;Enter End Number&quot;);
    int end = console.nextInt();
    System.out.println(&quot;The even numbers between &quot; + start + &quot; and &quot; + end + &quot; are the following:&quot;);

    int t = start % 2 == 1 ? start + 1: start;
    int sum = ((t + end) / 2) * ((end - t + 2) / 2);

    while(t &lt;= end) {
        System.out.println(t);
        t += 2;
    }
    
    System.out.println(&quot;The sum of even numbers between : &quot; + start + &quot; - &quot; + end + &quot; is : &quot; + sum);
}

Note: If we make the use of bit-wise operators we can make replace the following

  1. int t = start % 2 == 1 ? start + 1: start; by int t = start + (start &amp; 1);

  2. int sum = ((t + end) / 2) * ((end - t + 2) / 2); by int sum = ((t + end) &gt;&gt; 1) * ((end - t + 2) &gt;&gt; 1);

Final Solution

public static void main(String args[]) {
    Scanner console = new Scanner(System.in);
    System.out.println(&quot;Enter Start Number&quot;);
    int start = console.nextInt();
    System.out.println(&quot;Enter End Number&quot;);
    int end = console.nextInt();
    System.out.println(&quot;The even numbers between &quot; + start + &quot; and &quot; + end + &quot; are the following:&quot;);

    int t = start + (start &amp; 1);
    int sum = ((t + end) &gt;&gt; 1) * ((end - t + 2) &gt;&gt; 1);
    while(t &lt;= end) {
        System.out.println(t);
        t += 2;
    }
    System.out.println(&quot;The sum of even numbers between : &quot; + start + &quot; - &quot; + end + &quot; is : &quot; + sum);
}

答案7

得分: 0

int sum = 0;
for (int i = start; i <= end; i++) {
    if (i % 2 == 0) {
        sum += i;
    }
}
System.out.println(sum);
英文:
int sum = 0;
for(int i=start;i&lt;=end;i++){
   if(i%2==0){
      sum += i;
   }
}
System.out.println(sum);

答案8

得分: 0

    /**
     * C程序,打印从1到n之间所有偶数的和
     */
    
    #include <stdio.h>
    
    int main()
    {
        int i, n, sum=0;
    
        /* 从用户输入获取上限 */
        printf("输入上限:");
        scanf("%d", &n);
    
        for(i=2; i<=n; i+=2)
        {
            /* 将当前偶数添加到总和 */
            sum += i;
        }
    
        printf("1到%d之间所有偶数的和 = %d", n, sum);
    
        return 0;
    }
    
输出:-
输入上限:10
110之间所有偶数的和 = 30
英文:
/**
 * C program to print sum of all even numbers between 1 to n
 */

#include &lt;stdio.h&gt;

int main()
{
    int i, n, sum=0;

    /* Input upper limit from user */
    printf(&quot;Enter upper limit: &quot;);
    scanf(&quot;%d&quot;, &amp;n);

    for(i=2; i&lt;=n; i+=2)
    {
        /* Add current even number to sum */
        sum += i;
    }

    printf(&quot;Sum of all even number between 1 to %d = %d&quot;, n, sum);

    return 0;
}

Output:-
Enter upper limit: 10
Sum of all even number between 1 to 10 = 30

huangapple
  • 本文由 发表于 2020年10月18日 00:04:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64404472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定