4.1
package test1;
import java.util.Scanner;
// 第八版 第四章 课后编程题的答案 4.1
public class Test1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter an int value , the program exits if the input is 0:" );
int zcount=0;
int fcount=0;
double sum=0 ;
double average=0;
int number=1;
while(number!=0){
number=input.nextInt();
if(number>0) {
zcount++;
}
else if(number<0) {
fcount++;
}
sum=sum+number;
}
average=sum/(zcount+fcount);
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);
}
}
4.2
package test1;
import java.util.Scanner;
public class Test2 {
//4.2(重复加法)
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
int zcount=0;
int count=0;
Scanner input=new Scanner(System.in);
while(count<10) {
int number1=(int)(Math.random()*14+1);
int number2=(int)(Math.random()*14+1);
System.out.println("请问: "+number1+" + "+number2+" = ?");
int answer=input.nextInt();
if(number1+number2==answer) {
zcount++;
System.out.println("你是正确的!");
}else {
System.out.println("你是错误的!");
}
count++;
}
long endTime=System.currentTimeMillis();
long testTime=endTime-startTime;
System.out.println("正确的答案的个数为: "+zcount);
System.out.println("当前的时间为: "+testTime);
}
}
4.3
package test1;
public class Test3 {
//4.3
public static void main(String[] args) {
System.out.println("千克"+" "+"磅");
for(int i=1;i<=199;i=i+2) {
double pound=i*2.2;<