我的第五次java作业
题目:
二项分布是n次独立试验中成功次数k的离散概率分布,其中每次试验成功的概率为p。利用Java Math类中提供的数学函数,给出二项分布X~B(n, p, k)的实现代码并进行测试。例如,当用户给定n=20, p=0.1, k=5的概率应为0.03192136。
代码
package calculation;
import java.math.BigDecimal;
import java.util.Scanner;
public class calculation {
public static void main(String[] args)
{
Scanner sc=new Scanner (System.in);
System.out.println("请一次输入n.k.p");
int n=sc.nextInt();
int k=sc.nextInt();
double p=sc.nextDouble();
double result=(factorial(n)/(factorial(k)*factorial(n-k)))*(Math.pow(p, k))*(Math.pow((1-p), n-k));
double A=(factorial(n)/(factorial(k)*factorial(n-k)));
//System.out.println(Math.pow(p, (n-k)));
//System.out.println(Math.pow((1-p), k));
BigDecimal finalresult=new BigDecimal(result);
String ii=finalresult.toPlainString();
System.out.println(ii);//解决的问题是如何将double类型的结果的科学记数法表示形式转化为小数,
sc.close();
}
public static long factorial(int n)//阶乘函数
{
long result=n;
for(int i=n-1;i>=1;i--)
{
result=result*i;
}
return result;
}
}
问题与收获思考:
实验1:没有解决的问题是最后的结果保留小数的位数问题;
解决的问题是如何将double类型的结果的科学记数法表示形式转化为小数,运用了
import java.math.BigDecimal;
BigDecimal finalresult=new BigDecimal(result);
String ii=finalresult.toPlainString();
System.out.println(ii);
题目:
代码
package crap;
public class crap {
public static void main(String []args)
{
System.out.println("这是胡竞文(201911030235)的java作业");
System.out.println("现在开始掷骰子");
int firstround=play();
if(firstround==2 ||firstround==12||firstround==3)
{
System.out.println("you lose");
}
else if(firstround==7 ||firstround==11)
{
System.out.println("you win");
}
else
{
System.out.println("point is"+firstround);
int nextround=0;
nextround=play();
while(nextround!=firstround && nextround!=7)//就是这个地方出现了问题,要注意java中的循环不能好多个if后加else,可以用考虑用while循环改写
{
nextround=play();
}
if(nextround==7)
{System.out.println("you lose");}
else if(nextround==firstround)
System.out.println("you win");
}
}
public static int play()
{
int result=0;
int num1=(int)Math.ceil( 6*Math.random());
int num2=(int)Math.ceil( 6*Math.random());
result=num1+num2;
System.out.println("you roled"+num1+"+"+num2+"="+result);
return result;
}
}
问题与收获思考:
对于循环问题,我觉得最后这一句代码特别值得注意,
while(nextround!=firstround && nextround!=7)
一开始我写成了for循环
for(i=1; nextround==firstround ||nextround==7;i++)
但其实这个有多个错误,第一个错误是我应该用!=而不是==,终止条件的意思是当循环满足这个条件的时候会继续循环,不满足这个条件了才会挑出来,再一个,这个循环用while更好,i在里面没有起作用。再一个,我用错了符号,不应该用||,而应该用&&,因为两个判断条件都是否定,应该两个都不满足才在循环里,如果用||就表示两个中的任意一个满足或者都不满足就会继续循环,然而两个都不满足是一定的,所以就会一直在循环里,就造成了一开始无限循环的错误结果了。