整数之和

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

The sum of integers

问题

我想打印出从 a 到 b 之间所有整数的和,包括a和b。到目前为止,我停在这里:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i<=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}

我做错了什么?

英文:

I would like to print the sum of all integers from a to b containing both. So far I have stopped at this:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i&lt;=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}

What I am doing wrong?

答案1

得分: 3

让 b=200,a=195,根据您的逻辑,j=(200-195)=5。通过循环,总和将为1+2+3+4+5=15。但您需要的是195+196+197+198+199+200的总和。

循环应该如下所示:

 for(int i = a; i<=b ; i++){
        total+=i;
    }
英文:

Let b=200 and a=195, so according to your logic j=(200-195)=5. With the loop, the sum will be 1+2+3+4+5=15. But you need sum of 195+196+197+198+199+200.

The loop should go as:

 for(int i = a; i&lt;=b ; i++){
        total+=i;
    }

To understand how to debug a program please refer to https://techforhumans.site/java/right-way-to-debug-code-using-pen-and-paper/

答案2

得分: 1

这是您想要的吗?

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int total = 0;
        for(int i = a; i<=b ; i++){
            total+=i;
        }
        System.out.println(total);
    }

当然,这只在 a < b 的情况下有效。

英文:

Is this what you want?

    public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		int total = 0;
		for(int i = a; i&lt;=b ; i++){
			total+=i;
		}
		System.out.println(total);
	}

Of course this works only if a < b

答案3

得分: 1

你实际上没有将整数从 ab 相加 - 你是在将所有整数从 0a - b 相加。你的循环应该从 ab,而不是从 0a - b

考虑当 a 为5,b 为10的情况 - 你应该相加 5 + 6 + 7 + 8 + 9 + 10,但是你当前的算法却相加了 0 + 1 + 2 + 3 + 4 + 5。

英文:

You're not actually adding the integers between the a and b - you're adding all of the integers from 0 to a - b. Your loop should actually be from a to b, not 0 to a - b.

Consider the case where a is 5 and b is 10 - you should be adding 5 + 6 + 7 + 8 + 9 + 10, but instead your current algorithm adds 0 + 1 + 2 + 3 + 4 + 5.

huangapple
  • 本文由 发表于 2020年5月31日 00:25:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/62105403.html
匿名

发表评论

匿名网友

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

确定