代码改变世界

Java小程序4(2015-8-10)

2015-08-10 15:26  马尔代夫_珍  阅读(200)  评论(0编辑  收藏  举报

一、从键盘输入一个正整数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);

 } }