Java 分别用do-while和for循环计算1+1/2!+1/3!+1/4!… … 的前20项和。

public class Example1_3 {
    public static void main(String args[]) {
        double a = 1, b = 1, c = 0;
        System.out.println("do-while循环:");
        do {
            c = b + c;
            a++;
            b = (1.0 / a) * b;
        } while (a <= 20);
        System.out.println(" " + c);
        System.out.println("for循环:");
        for (c = 0, b = 1, a = 1; a <= 20; a++) {
            b *= (1.0 / a);
            c += b;
        }
        System.out.println(" " + c);
    }
}

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目 录 实验1 Java语言基础 实验2 数组和字符串编程 实验3 Java面向对象程序设计 实验4 Java异常处理 实验5 多线程编程 实验6 图形用户界面编程 实验7 输入与输出 实验8 网络编程 实验9 数据库编程 实验1 Java语言基础 一、实验目的和要求 1.实验目的 通过实验,掌握Java语言程序设计的基本方法。 学会Java语言中标示符的命名、运算符和表达式的应用。 熟练地掌握Java程序流程控制语句的应用。 2.实验内容 1.编写应用程序,计算100(含100)以内所有偶数的和。 2."水仙花数"是指一个3位数,其个位、十位、百位上的数字的立方和等于该数本身,例 如371=33+73+13,因此371是一个水仙花数。编写程序,求所有的水仙花数。 3.编写一个程序,求1-100间的素数。 4.有一函数: x (x<1) Y= 3x-2 (1 x<10) 4x (x 10) 写一程序,给定x值,输出y值。 5.使用for循环语句,编写程序输出以下图案。 6.编写程序,输出从公元1900年到2100年所有闰年的年号,每输出5个年号换一行。判断 年是否为闰年的条件是: 若年号可以被4整除,而不能被100整除,则是闰年; 若年号可以被400整除,也是闰年。 二、源代码 1.package addsum; public class addsum { public static void main(String s[]) { int sum=0; for(int i=0;i<=100;i=i+2) sum=sum+i; System.out.println(sum); } } 2.package addsum; public class shuixianhua { public static void main(String[] args) { int i, j, k; for (i = 1; i <= 9; i++) { for (j = 0; j <= 9; j++) { for (k = 0; k <= 9; k++) { if ((i * 100 + j * 10 + k) == (i * i * i + j * j * j + k * k * k)) System.out.println(i * 100 + j * 10 + k + "=" + i + "*" + i + "*"+i+"+" + j + "*" + j+ "*" + j + "+" + k+ "+" + k+ "+" + k); } } } } } 3.package addsum; public class prime { public static void main(String[] args) { System.out.println("100内的素数为:"); loop: for (int i = 2; i < 100; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue loop; } } System.out.print(" " + i); } } } 4.package addsum; import java.util.Scanner; public class question4 { public static void main(String[] args) { double x,y; System.out.print("请输入x:"); do{ Scanner s=new Scanner(System.in); x=s.nextDouble(); if(x<1) y=x; else if(x>=1&&x<10) y=3*x-2; else y=4*x; System.out.println("x="+x+","+"y="+y); } while(true); } } 5.package addsum; public class question5 { public static void main(String args[]){ for(int r=1; r<=4; r++) {for (int space=4-r; space>0; space--) System.out.print(""+" "+""); for(int star=1; star<=2*r-1; star++) System.out.print(' '); System.out.print('\n'); } for(int r=3; r>=1; r--) {for(int space=4-r; space>0; space--) System.out.print(""+" "+

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值