问答详情
源自:4-2 Java条件语句之 if...else

条件语句if...else

设int n ,打印1+3+5+...+n,当n为奇数,则累加到n,若为偶数,则累加到n-1,变量n的初始值在程序中指定

提问者:玖柒LN 2020-05-23 13:24

个回答

  • 大猫喔
    2020-07-07 20:39:46

    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);

    }


  • 一纸三言两语
    2020-06-18 08:09:56

    上面n为偶数时,条件应该为i<=n-1;等于号忘写了

  • 一纸三言两语
    2020-06-18 07:34:37

    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);

    }

    }


    }


  • qq_慕移动2467453
    2020-05-26 15:20:28

    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);

    }

    }