(5.2~5.7节)+(5.8~5.10节)
(综合题的答案还没有写)
*5.1(统计正数和负数的个数然后计算这些数的平均值)
import java.util.Scanner;
public class F1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter an integer, the input ends if it is 0:");
int number=input.nextInt();
int count=0;
int zcount=0;
int fcount=0;
double sum=0;
double average=0;
if(number!=0) {
while(number!=0) {
count++;
if(number>0) {
zcount++;
}
else {
fcount++;
}
sum+=number;
average=sum/count;
number=input.nextInt();
}
System.out.println("The number of positives is "+zcount);
System.out.println("The number of negatives is "+fcount);
System.out.println("The total is "+sum);
System.out.println("The average is "+average);
}
else if(number==0) {
System.out.println("No numbers are entered except 0");
}
input.close();
}
}
5.2(重复加法)
import java.util.Scanner;
public class F2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
long startTime=System.currentTimeMillis();
int rightCount=0;
String output="";
int count=0;
while(count<10) {
int random1=(int) (1+Math.random()*15);
int random2=(int) (1+Math.random()*15);
System.out.print("请问:"+random1+"+"+random2+" = ? ");
int answer=input.nextInt();
if(answer==(random1+random2)) {
System.out.println("You are right.");
rightCount++;
}
else {
System.out.println("You are wrong!"+" answer shoule be "+(random1+random2));
}
count++;
output+="\n"+random1+" + "+random2+" = "+answer+" "
+((answer==random1+random2)?"correct":"wrong");
}
long endTime=System.currentTimeMillis();
long textTime=endTime-startTime;
System.out.println(output);
System.out.println("正确答案个数:"+rightCount);
System.out.println("测验时间为:"+textTime/1000+" seconds");
input.close();
}
}
5.3(将千克转换成磅)
public class F3 {
public static void main(String[] args) {
System.out.println("千克 磅");
for(int i=1; i<=199; i++) {
System.out.printf("%-3d %5.1f \n", i, 2.2*i);
}
}
}
5.4(将英里转换为千米)
public class F4 {
public static void main(String[] args) {
System.out.println("英里 千米");
for(int i=1; i<=10; i++) {
System.out.printf("%-2d %-6.3f \n", i, i*1.609 );
}
}
}
5.5(千克与磅之间的互换)
小伙伴肯定一开始也和我一样想到用嵌套循环,可是后面一运行,才恍然大悟。