接下来写一下今晚做的笔试题
题目描述
小明回到家中,他想编程计算数学期望,你能帮助他么?
输入
输入第一行一个数n(1<=n<=100),接下来有n行,第i行有两个数xi和pi,xi和pi都是整数,-100<=xi<=100, 0<=pi<=100。表示随机变量X取值为xi的概率是pi/100。输入保证p1+p2+p3+…+pn=100。
|
样例输入
3 0 50 1 20 2 30
|
输出
输出一个数,随机变量X的数学期望E[x],小数点后四舍五入保留3位。
|
样例输出
0.800
|
时间限制
C/C++语言:2000MS
其它语言:4000MS
|
内存限制
C/C++语言:65536KB
其它语言:589824KB
|
这道题的思路很简单,无非就是从键盘读入一个数,然后建两个数组分别保 Xi和Pi,之后再建个数组Si存储他俩的乘积,最后Si求和/100.
我卡住的点:
1.从键盘读入掌握的不好
2.保留三位小数处理的不好。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //标准化输入
int n = sc.nextInt(); //从键盘读int型
int[] x = new int[n];
int[] pi = new int[n];
for(int i=0;i<n;i++){
x[i] = sc.nextInt();
pi[i] = sc.nextInt();
}
double res = 0.0;
for(int j=0;j<n;j++){
res +=x[j]*pi[j]/100.0;
}
System.out.println(String.format("%.3f",res));//转化为保留三位小数
/*
保留3位小数或者可以这样处理
DecimalFormat df = new DecimalFormat("#0.000");
System.out.println(df.format(result));
*/
}
}
[java] view plain copyprint?
- importjava.text.DecimalFormat;
-
- publicclassTestNumberFormat{
-
- publicstaticvoidmain(String[]args){
- doublepi=3.1415927; //圆周率
- //取一位整数
- System.out.println(newDecimalFormat("0").format(pi)); //3
- //取一位整数和两位小数
- System.out.println(newDecimalFormat("0.00").format(pi)); //3.14
- //取两位整数和三位小数,整数不足部分以0填补。
- System.out.println(new DecimalFormat("00.000").format(pi));// 03.142
- //取所有整数部分
- System.out.println(newDecimalFormat("#").format(pi)); //3
- //以百分比方式计数,并取两位小数
- System.out.println(new DecimalFormat("#.##%").format(pi)); //314.16%
-
- longc=299792458; //光速
- //显示为科学计数法,并取五位小数
- System.out.println(newDecimalFormat("#.#####E0").format(c)); //2.99792E8
- //显示为两位整数的科学计数法,并取四位小数
- System.out.println(newDecimalFormat("00.####E0").format(c)); //29.9792E7
- //每三位以逗号进行分隔。
- System.out.println(newDecimalFormat(",###").format(c)); //299,792,458
- //将格式嵌入文本
- System.out.println(newDecimalFormat("光速大小为每秒,###米。").format(c));
- }
- }
Scanner是SDK1.5新增的一个类,可是使用该类创建一个对象.
Scanner reader=new Scanner(System.in);
然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型
next.Byte()
nextDouble()
nextFloat
nextInt()
nextLine()
nextLong()
nextShot()
上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.例如,拥护在键盘输入
12.34,hasNextFloat()的值是true,而hasNextInt()的值是false. NextLine()等待用户输入一个文
本行并且回车,该方法得到一个String类型的数据。
简单来说,就是next后面跟什么类型的数据,就读取什么类型的。