java语言程序设计第五章答案_Java语言程序设计(基础篇)原书第十版 课后习题 第五章...

import java.util.Scanner;public class Code_Practice_5 {public static void main(String[] args) {// 5.1Scanner input = new Scanner(System.in);System.out.print("Enter an integer, the input ends if it is ...
摘要由CSDN通过智能技术生成

import java.util.Scanner;

public class Code_Practice_5 {

public static void main(String[] args) {

// 5.1

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer, the input ends if it is 0:");

int number = input.nextInt();

int countP = 0, countN = 0;

int total = 0, count = 0;

if (number != 0) {

// 如果写成while(true),会出现Unreachable code的问题,原因没找到

while (number != 0) {

if (number > 0)

countP++;

else

countN++;

total += number;

number = input.nextInt();

}

double average = total / (countP + countN);

System.out.println("The number of positives is " + countP);

System.out.println("The number of negatives is " + countN);

System.out.println("The total is " + total);

System.out.println("The average is " + average);

}

else

System.out.println("No numbers are entered except 0");

// 5.2

final int NUMBER_OF_QUESTIONS = 5; // Number of questions

int correctCount = 0 ; // Count the correct

int count = 0; // Count the questions

long startTime = System.currentTimeMillis();

String output = " "; // output string is initially empty;

Scanner input = new Scanner(System.in);

while (count < NUMBER_OF_QUESTIONS) {

// Generate two random single-digit integers

int num1 = (int)(1 + Math.random() * 14);

int num2 = (int)(1 + Math.random() * 14);

System.out.print(

"What is " + num1 + "+" + num2 + " ? ");

int answer = input.nextInt();

if (num1 + num2 == answer){

System.out.println("You are correct!");

correctCount ++;

}

else

System.out.println("Your answer is wrong.\n" + num1

+ "+" + num2 + " should be " + (num1 + num2));

count ++;

output += "\n" + num1 + "+" + num2 + "=" + answer +

((num1 + num2 == answer) ? " correct" : " wrong");

}

long endTime = System.currentTimeMillis();

long testTime = endTime - startTime;

System.out.println("\nCorrect count is " + correctCount +

"\nTest time is " + testTime / 1000 + " seconds\n" + output);

// 5.3

int kilo = 1;

double pound = 0;

System.out.println("千克" + " " + " 磅");

for (int i = 0; i < 199; i++) {

System.out.print(kilo);

pound = kilo * 2.2;

System.out.printf("%12.1f\n", pound);

kilo++;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值