最大值计算过程(Find the Largest Number)

时间:2022-09-06 18:32:42

算是超简单的问题了吧,Excel中用一个max()函数就能搞定的问题,我要写这么长代码才实现。

不过,写代码有一种*的感觉。在找到最大值的同时,可以告诉你最大值在哪里。(相信Excel也有相应功能最大值计算过程(Find the Largest Number)

补记:

Excel中查找一列数据中的最大值所在行,公式为:INDEX(A:A,MATCH(MAX(B:B),B:B))


代码如下:

//JHTP Exercise 4.21: Find the Largest Number
//by pandenghuang@163.com
/* (Find the Largest Number) The process of finding the largest value is used frequently in computer
*applications. For example, a program that determines the winner of a sales contest would input
*the number of units sold by each salesperson. The salesperson who sells the most units wins the contest.
*Write a pseudocode program, then a Java application that inputs a series of 10 integers and determines
*and prints the largest integer. Your program should use at least the following three variables:
*a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been
*input and to determine when all 10 numbers have been processed).
*b) number: The integer most recently input by the user.
*c) largest: The largest number found so far.*/

import java.util.Scanner;

public class Test {

	public static void main(String[] args) {
		int counter=1;
		int largest=0;
		Scanner scanner=new Scanner(System.in);
		int number=0;
		int salesNo=1;
		int maxSalesNo=1;
		
		while (counter<=10){
			
			System.out.printf("请输入销售员No.%d的销售额:",salesNo);
			number=scanner.nextInt();
			if(number>=largest)
			{largest=number;
			maxSalesNo=salesNo;
			}
			++counter;
			++salesNo;
		}
		System.out.printf("恭喜销售员No.%d创造了最高销售额:%d RMB",maxSalesNo,largest);
		}
}


运行结果:

请输入销售员No.1的销售额:1
请输入销售员No.2的销售额:2
请输入销售员No.3的销售额:3
请输入销售员No.4的销售额:9
请输入销售员No.5的销售额:8
请输入销售员No.6的销售额:7
请输入销售员No.7的销售额:6
请输入销售员No.8的销售额:5
请输入销售员No.9的销售额:4
请输入销售员No.10的销售额:2
恭喜销售员No.4创造了最高销售额:9 RMB