用Java 编写1-1/2+1/3-1/4+---------+(-1)(n-1) *1/n,其中n是用户输入的正整数

[复制链接]
查看11 | 回复2 | 2009-12-24 12:12:54 | 显示全部楼层 |阅读模式
public class Test { public double getResult(int n) {boolean isAdd = true;double x = 0.0;for(int i=1;i<n+1;i++){ if(isAdd) {x+=(double)1/i;isAdd = false;} else {x-=(double)1/i;isAdd = true;}}return x; } public static void main(String[] args) {System.out.println(new Test().getResult(10)); }}
回复

使用道具 举报

千问 | 2009-12-24 12:12:54 | 显示全部楼层
public class Test { public static void main(String[] args) {int n = 4;double sum = 1.0;for (int i = 2; i <= n; i++) { if (i % 2 == 0) {
sum = sum - 1.0 / i; } else {
sum = sum + 1.0 / i; }}System.out.println(sum); }}
回复

使用道具 举报

千问 | 2009-12-24 12:12:54 | 显示全部楼层
public jiechengjiaochaqiuhe {public static voidmain(String args[]){ double odd_sum, even_sum; float max, count, sign; odd_sum =0.0; even_sum = 0.0;
sign=-1; System.out.print("please enter the max float number\n");System.in(max); for(count=1.0; count <= max; count +=1.0) {odd_sum = odd_sum + 1.0/count;sign=-sign;even_sum = even_sum + sign/count; }}} System.out.println( odd_sum, even_sum);}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行