所以我正在研究这个问题,用户输入数字 X,结果是 0 和 X 之间的所有数字的总和,以这种方式计算:
- 7的倍数和11的倍数不计算在内。
- 但包括 7 和 11 的倍数,例如:77
例如:
用户输入 X >> 80
总和>> (0+1+2+3+....77) - (7,11,14,21,22....77) + (77) = 结果
import java.util.Scanner;
public class testadd {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please the number greater than 77");
// int a = 0;
int b = keyboard.nextInt();
int sum = 0;
int s = Math.min(0, b);
int e = Math.max(0, b);
System.out.println(s);
System.out.println(e);
int x=0;
for(int i=1; i<e; i++){
if(i%7 ==0 || i%11 ==0){
x=x+i;
System.out.println(x + " values of x");
}
}
while (s <= e) {
sum += s;
s++;
}
System.out.print("The sum of the numbers between " + 0 + " and " + b + " is " + sum);
}
}
最佳答案
您只需要一个循环就可以遍历从 1
到 e
的所有数字。检查可被 7
或 11
整除但不能被两者整除的数字的一种优雅方法是使用 ^
(异或)运算符:
long sum = 0;
for (int i = 1; i <= e; ++i) {
if (!((i % 7 == 0) ^ (i % 11 == 0))) {
sum += i;
}
}
关于java - 加法和减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31901758/