zoukankan      html  css  js  c++  java
  • Java小程序4(2015-8-10)

    一、从键盘输入一个正整数n,求1+2+3+...+n之和并输出。

    1、

    import java.util.Scanner;

    public class Test55{     

           public static void main(String [] args){       

                    System.out.println("请输入一个正整数n:");     

                    Scanner sc=new Scanner(System.in);     

                    int n=sc.nextInt();

                     int i;      

                     int sum=0;     

                          for(i=1;i<=n;i++)                  

                                 sum+=i;          

                  System.out.println("1+2+3+...+n之和为:"+sum);

    }}

    2、

    import java.util.Scanner;

    public class FiveTest{
     public static void main(String[] args){
      int a = 1;
      int sum = 0;
      Scanner scan = new Scanner(System.in);
      int n = scan.nextInt();
      while(a<=n){
       sum = sum + a;
       
       a++;
      }
      System.out.println(sum);
     }
    }

    二、 求1到100之间的奇数之和与偶数之和。

    public class SixTest{  

               public static void main(String[] args){   

                              int js = 0;  

                              int os = 0;  

                              int a = 1;

                   while(a<=100){   

                                     if(a%2==0){

                                              os+=a;   

                                     }else{   

                                              js+=a;    

                                    }   

                                 a++;   }  

                   System.out.println("奇数和为:"+js);  

                   System.out.println("偶数和为:"+os);

     } }

  • 相关阅读:
    3. applicationCache
    9. 水平垂直居中的方法
    2. 贝塞尔曲线bezierCurveTo
    相识python 之小数据池 集合
    相识python --------- 列表 元祖 range 范围
    相识python while循环 代码块 编码初识 运算符
    相识python第二步:变量 注释 str int bool 用户交换 流程控制语句的解释用法
    python学习基础知识
    python的基础知识
    我对python的见解
  • 原文地址:https://www.cnblogs.com/Ly426/p/4718129.html
Copyright © 2011-2022 走看看