条件语句if...else
设int n ,打印1+3+5+...+n,当n为奇数,则累加到n,若为偶数,则累加到n-1,变量n的初始值在程序中指定
设int n ,打印1+3+5+...+n,当n为奇数,则累加到n,若为偶数,则累加到n-1,变量n的初始值在程序中指定
2020-05-23
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int cot = 0;
if(num%2==0) {
for(int i=1;i<=num-1;i=i+2) { //i每次循环加2,直到i等于num-1,停止
cot = cot + i;
}
System.out.println("n为偶数,从1加到n-1之和为:" + cot);
}else {
for(int i=1;i<=num;i=i+2) {
cot = cot +i;
}
System.out.println("n为奇数,从1加到n-1之和为:" + cot);
}
public class Test_if_else {
public static void main(String[] args) {
// TODO Auto-generated method stub
//打印1+3+5+...+n,当n为奇数,则累加到n,若为偶数,则累加到n-1,变量n的初始值在程序中指定
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字:");
int n = sc.nextInt();
int sum=0;
if(n%2==0) {
for(int i=1;i<n-1;) {
sum+=i;
i+=2;
}
System.out.print(sum);
}else {
for(int i=1;i<=n;) {
sum+=i;
i+=2;
}
System.out.println(sum);
}
}
}
举报