java程序,计算级数1/2+2/3+3/4+...+99/100
关注:158 答案:5 mip版
解决时间 2021-01-12 19:33
提问者一种小幸福
2021-01-12 07:23
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类写好,然后根据那个级数写测试程序
最佳答案
二级知识专家降猪十八掌
2021-01-12 08:03
这样吧,你把要计算的整型数int转化成double型的如1/2转成1/2.0如此结果就是0.5了,这样计算就OK了!
全部回答
1楼無字情書
2021-01-12 11:51
要这么复杂?浮点数不就好了吗?
2楼傻ㄋ吧唧
2021-01-12 11:09
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);
}
3楼嶒經忲氾濫
2021-01-12 09:51
你目的是什么?程序有问题还是咋滴?
4楼久别无恙
2021-01-12 08:42
你在搞什么飞机 贴个程序 啥都不说
我要举报
如以上问答内容为低俗/色情/暴力/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
→点此我要举报以上信息!←
推荐资讯
大家都在看