英文:
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<=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<=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<=b ; i++){
total+=i;
}
System.out.println(total);
}
Of course this works only if a < b
答案3
得分: 1
你实际上没有将整数从 a
到 b
相加 - 你是在将所有整数从 0
到 a - b
相加。你的循环应该从 a
到 b
,而不是从 0
到 a - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论