2008年3月27日 星期四

Homework 3-24-2008

1. Based on your study of Display 3.8, write a code to find the max and min of a list of number.For example, given 1,3,5, and9, the max is 9 and the min is 1.Your program should be able to process a list of any length.

程式:
import java.util.Scanner;

public class Homework0324
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a list of nonnegative number:");
System.out.println("Mark the end with a negative number!");
System.out.println("I will show the max and min number!");

double number,max,min;
number=keyboard.nextDouble();
max=number;
min=number;

while (number>=0)
{
if(number>=max)
max=number;
if(number<=min)
min=number;
number=keyboard.nextDouble();
}
System.out.println("the max of three number is : "+max);
System.out.println("the min of three number is : "+min);
}
}

結果:










2. Write a program to generate the series 1, 1, 2, 3, 5, 8, 13, ...The series has a property that the third number is the sum of the first and second numbers. For example, 2=1+1, 3=1+2, and 5=2+3.


程式:
import java.util.Scanner;

public class Homework0324_2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter the limit number:");

int first,second,temp,max;

first=1;
second=1;
max=keyboard.nextInt();

System.out.print(first+" ");
System.out.print(second+" ");

while(second<=max)
{
temp=first+second;
first=second;
second=temp;
System.out.print(temp+" ");
}
}
}

結果:

沒有留言: