java程序,计算级数1/2+2/3+3/4+...+99/100
importjava.math.BigInteger;importjava.math.BigDecimal;publicclassRationalextendsNumbe...
import java.math.BigInteger;
import java.math.BigDecimal;
public class Rational extends Number implements Comparable{
private BigInteger numerator;
private BigInteger denominator;
public Rational()
{
this(new BigInteger("0"),new BigInteger("1"));
}
public Rational(BigInteger numerator,BigInteger denominator)
{
BigInteger gcd=gcd(numerator,denominator);
this.numerator=((denominator.compareTo(new BigInteger("0"))>0)?new BigInteger("1"):new BigInteger("-1")).multiply(numerator).divide(gcd);
this.denominator=denominator.abs().divide(gcd);
}
private static BigInteger gcd(BigInteger x1,BigInteger y1)
{
if(x1.compareTo(new BigInteger("0"))==0||y1.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
BigInteger x=x1.abs();
BigInteger y=y1.abs();
BigInteger m,n,t;
if(x.compareTo(y)>0)
{
m=x;
n=y;
}
else
{
n=x;
m=y;
}
while(m.mod(n).compareTo(new BigInteger("0"))!=0)
{
t=n;
n=m.mod(n);
m=t;
}
return n;
}
部分Rational类
怎么写测试程序,就是Rational类写好,然后根据那个级数写测试程序 展开
import java.math.BigDecimal;
public class Rational extends Number implements Comparable{
private BigInteger numerator;
private BigInteger denominator;
public Rational()
{
this(new BigInteger("0"),new BigInteger("1"));
}
public Rational(BigInteger numerator,BigInteger denominator)
{
BigInteger gcd=gcd(numerator,denominator);
this.numerator=((denominator.compareTo(new BigInteger("0"))>0)?new BigInteger("1"):new BigInteger("-1")).multiply(numerator).divide(gcd);
this.denominator=denominator.abs().divide(gcd);
}
private static BigInteger gcd(BigInteger x1,BigInteger y1)
{
if(x1.compareTo(new BigInteger("0"))==0||y1.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
BigInteger x=x1.abs();
BigInteger y=y1.abs();
BigInteger m,n,t;
if(x.compareTo(y)>0)
{
m=x;
n=y;
}
else
{
n=x;
m=y;
}
while(m.mod(n).compareTo(new BigInteger("0"))!=0)
{
t=n;
n=m.mod(n);
m=t;
}
return n;
}
部分Rational类
怎么写测试程序,就是Rational类写好,然后根据那个级数写测试程序 展开
展开全部
public static double getResult(int n)
{
return (double)n/(n+1);
}
public static void main(String[] args) throws IOException
{
double sum = 0.0d;
for(int i = 1; i < 99; i ++)
{
sum += getResult(i);
}
System.out.println("所求值: " + sum);
}
{
return (double)n/(n+1);
}
public static void main(String[] args) throws IOException
{
double sum = 0.0d;
for(int i = 1; i < 99; i ++)
{
sum += getResult(i);
}
System.out.println("所求值: " + sum);
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
这样吧,你把要计算的整型数int转化成double型的如1/2转成1/2.0如此结果就是0.5了,这样计算就OK了!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你在搞什么飞机 贴个程序 啥都不说
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
要这么复杂?浮点数不就好了吗?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你目的是什么?程序有问题还是咋滴?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询