我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*Filename:P6Q02
* Name:Wang Chaoran
Description:2 (Alternative solution to Listing 6.1, TestArray.java)
The solution of Listing 6.1 counts the occurrences of the largest number by
comparing each number with the largest. So you have to use an array to store
all the numbers. Another way to solve the problem is to maintain two variables,
max and count. max stores the current max number, and count stores its occurrences.
Initially, assign the first number to max and 1 to count. Compare each subsequent number
with max. If the number is greater than max, assign it to max and reset count to 1.
If the number is equal to max, increment count by 1. Use this approach to rewrite Listing 6.1.
*/
import java.util.Scanner;
class P6Q02{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double[] input = new double[6];
System.out.println("Please input number "+1+": ");
input[0] = scan.nextDouble();
int count = 1;
double max = input[0];
for(int i = 1; i < input.length; i++){
System.out.println("Please input number "+(i+1)+": ");
input[i] = scan.nextDouble();
if(input[i]>max){
count = 1;
max = input[i];
}
else if(input[i]==max)
count++;
}
System.out.println("Max is: "+max);
System.out.println("Number of occurrence: "+count);
}
}
导入论坛查看(37)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing