交替加减一个数java
Alternate adding and subtracting a number java
这是我当前的代码:
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
你快到了:
for (int i = 1; i <= n; i++) {
if (i > 2 && i % 2 != 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
前两个数字对带有 "plus" 符号的结果有贡献,它们的符号不会交替,因此附加 i > 2
条件。
旁注: 我建议将 sum
重命名为 result
并将输出文本更改为 System.out.println("The result is:"+result);
之类的内容。
原因是计算的不是sum,名字sum
有点乱。
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++;
}
或:
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
价值
烦恼
int result = 0;
for (int i = 1; i <= n; i++) {
int num = input.nextInt();
result += (i == 1 || i % 2 == 0) ? num : -num;
}
这是我当前的代码:
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
你快到了:
for (int i = 1; i <= n; i++) {
if (i > 2 && i % 2 != 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
前两个数字对带有 "plus" 符号的结果有贡献,它们的符号不会交替,因此附加 i > 2
条件。
旁注: 我建议将 sum
重命名为 result
并将输出文本更改为 System.out.println("The result is:"+result);
之类的内容。
原因是计算的不是sum,名字sum
有点乱。
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++;
}
或:
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
价值
int result = 0;
for (int i = 1; i <= n; i++) {
int num = input.nextInt();
result += (i == 1 || i % 2 == 0) ? num : -num;
}