JAVA语言程序设计(基础篇) 第十版——第五章 循环 (参考答案)

(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(千克与磅之间的互换)

小伙伴肯定一开始也和我一样想到用嵌套循环,可是后面一运行,才恍然大悟。

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值