玖柒LN
2020-05-23 13:24
设int n ,打印1+3+5+...+n,当n为奇数,则累加到n,若为偶数,则累加到n-1,变量n的初始值在程序中指定
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);
}
上面n为偶数时,条件应该为i<=n-1;等于号忘写了
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);
}
}
}
package com.imooc;
public class helloword {
public static void main (String[] args) {
int sum = 0;
for (int i = 1;i<=100;i++)
{
if ( i%2 ==0 ) {
continue;
}
sum = sum + i;
}
System.out.println("100以内基数和为"+sum);
}
}
Java入门第一季(IDEA工具)升级版
1165172 学习 · 17581 问题
相似问题