package Basics;
import java.util.Scanner;
public class ForLoop {
public static void main(String args[]){
Scanner Jee = new Scanner(System.in);
int Final = 0;
int HowManyRounds = 1;
for (int counter = 1; counter <= HowManyRounds; counter++){
System.out.println("Type your boundary: ");
int Limit = Jee.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = Jee.nextInt();
System.out.println("Type your starting number: ");
int StartingNumber = Jee.nextInt();
for(int Answer = StartingNumber; Answer <= Limit;Answer += number){
Final += Answer;
}
}
System.out.println(Final);
Jee.close();
}
}
我回答错了。我不知道为什么。当我输入1000为边界5为圆形和0为起始数字时,我应该得到99500但我得到100500当我输入1000 3 0时,我得到正确的答案我在哪里得到相同的答案99 3 0 ......
输入您的边界: 1000 在给定边界中键入您想要所有倍数之和的数字: 五 输入您的起始号码: 0 100500
输入您的边界: 1000 在给定边界中键入您想要所有倍数之和的数字: 3 输入您的起始号码: 0 166833
输入您的边界: 999 在给定边界中键入您想要所有倍数之和的数字: 3 输入您的起始号码: 0 166833
答案 0 :(得分:1)
如果您希望在第一种情况下得到99500的答案,这可能意味着您不希望在您的操作中包含限制本身(您现在正在执行此操作)。尝试更改for循环中的条件以回答&lt;限制(而不是&lt; =):
for(int Answer = StartingNumber; Answer < Limit;Answer += number){
[...]
答案 1 :(得分:0)
开始新循环时,您不会将Final
归零。
相反,在循环中移动Final
的声明:
for (int counter = 1; counter <= HowManyRounds; counter++){
int Final = 0; // now Final is zeroed automatically for every iteration
// rest of loop the same
}
请遵循java命名约定:变量shoiuld以小写字母开头,即int total
,而不是int Total
你似乎无法完成这项工作。这是修复的整个方法,包括修复样式问题。无论逻辑是否正确,我都不能说,因为你没有告诉我们你在做什么。
private static final int ROUNDS = 3;
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < ROUNDS; i++) {
System.out.println("Type your boundary: ");
int limit = keyboard.nextInt();
System.out.println("Type the number which you want the sum of all multiples in given boundary: ");
int number = keyboard.nextInt();
System.out.println("Type your starting number: ");
int start = keyboard.nextInt();
int total = 0;
for (int n = start; n <= limit; n += number) {
total += n;
}
System.out.println(total);
}
keyboard.close();
}