如何在循环中计算min,max(java)

时间:2012-12-03 14:08:22

标签: java eclipse loops while-loop min

我在为toomorow讲座编写1个应用程序时遇到问题。

所以, 该程序要求用户输入数字,键入“100”它会停止,并显示: -平均 -min -max

我知道我需要使用什么样的循环(do-while right?)。 但我如何在不使用数组的情况下计算平均值,最小值,最大值?

3 个答案:

答案 0 :(得分:2)

Step 1 : user three temp variable 
Step 2 : initialize three temp variable(min,max,avg all by 0)
Step 1 : inside the loop if temp > max ==>> max = temp
Step 1 : inside the loop if temp < min ==>> min = temp
Step 1 : avg = ( avg + temp )/i

int[] values = { .. values .. }

int min=0,max=0,avg = 0;
for(int i=1;i<=values.length;i++)
{
if(min > values[i])
min = values[i] 
if(max < values[i])
max = values[i] 
avg = ( avg + values[i] ) / i
}

答案 1 :(得分:1)

这是速记伪代码,因为你必须自己编写代码:

min = max = total = user_input
count = 0
do {
    count++
    input = get_input
    total += input
    min or max maybe = input
} while (input !=100)
average = total / count
print stuff
祝你好运

答案 2 :(得分:1)

我可以告诉你如何在没有数组的情况下计算平均最小值和最大值。但是,我无法告诉您如何计算平均最小值和最大值WITH数组。

最低限度很简单:

int current_min
ArrayList<int> find_min = new ArrayList<int>();
for (int c : find_min)
    if (c < current_min)
        current_min = c;

最大值有点难度。你需要使用“功能”

boolean check_if_integer_is_bigger_than_another_integer(int another_integer_to_check_against, int the_original_integer_goes_here_into_this_argument_here)
{
    if (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here)
    return (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here) //Important
    return (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here)
}
    int current_max
    ArrayList<int> find_max = new ArrayList<int>();
    for (int c : find_max)
        if (check_if_integer_is_bigger_than_another_integer(c, current_max))
            current_max = c;

我甚至不想进入平均值。你必须添加数字,但我并不完全符合这一要求。