这是我目前的代码:
Scanner input = new Scanner(System.in);
int n, sum = 0;
System.out.println("Enter n:");
n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
System.out.println("The total sum is:"+sum);
有人可以帮助交替添加和减去整数吗?
例如,如果我输入n: = 5
并要求用户输入4, 14, 5, 6, 1
,那么它将计算为4 + 14 - 5 + 6 - 1
答案 0 :(得分:3)
你快到了那里:
for (int i = 1; i <= n; i++) {
if (i > 2 && i % 2 != 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
前两个数字对带有“加号”的结果有贡献,它们的符号不会交替,因此会增加i > 2
条件。
旁注:我建议将sum
重命名为result
,并将输出文本更改为System.out.println("The result is:"+result);
。
原因是它不是 sum 被计算,名称sum
有点令人困惑。
答案 1 :(得分:1)
ReplaySubject
答案 2 :(得分:0)
int result = 0, n, i = 2;
result = input.nextInt(); // initialise result with first value
boolean add = true;
while(i <= n){
int num = input.nextInt();
if(add){
result += num;
}else{
result -= num;
}
add = !add // flip the value of boolean flag
i++;
}
OR:
int result = 0, n, i = 2;
result = input.nextInt(); // initialise result with first value
boolean add = true;
while(i <= n){
int num = input.nextInt();
if(!add){
num *= -1;
}
result += num;
add = !add // flip the value of boolean flag
i++;
}
修改:而不是添加前两个值,
使用第一个值初始化结果,然后交替add
标志。无需担心i's
值