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

     } }

  • 相关阅读:
    关于SQL Server 2005 SP2中提供的Vardecimal存储格式
    .NET平台网络编程之最佳实践 【转载】
    如果类型转换无可避免,那么应该尽可能用as运算符,而不是强制转换
    ArraySegment 的使用 【转载】
    如果不写Order By子句,会怎么样
    ToString 的几个思考
    尽量用属性(Property),而不是字段(Field)
    如何设置SQL Server服务器上面的CPU占用过高的警报
    SQL Server 2008 Replication and Filestream, are both supported together?【转载】
    Microsoft Sync Framework
  • 原文地址:https://www.cnblogs.com/Ly426/p/4718129.html
Copyright © 2011-2022 走看看