题目要求:要求计算1-2+3-4+5-6...+n。源码加详细解释如下:
import java.util.Scanner;
//计算1-2+3-4+5-6+7-8+9-10的值
public class jiajian {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入要计算的值:");
Scanner ns = new Scanner(System.in);
int s = ns.nextInt();
amount(s);
}
//定义计算方法
public static void amount(int n){
String msg = "";//用于保存答案的前缀
int count = 0;//用于保存得到的计算结果
for(int i=0;i<=n;i++){
int s;
if(i%2==0){
s = -i;
msg = msg+s;
}else{
s = i;
msg = msg+"+"+s;
}
count = count+s;
}
System.out.print(msg+"="+count);
}
}