识别偶数,奇数,最大和最小数字

时间:2016-09-08 23:28:55

标签: java

所以,我已经弄清楚如何计算输入的整数和平均数;但是,我似乎无法弄清楚如何找出最大,最小,偶数和奇数。我尝试了几件事,但它不起作用。

任何提示或建议?我不需要你为我写任何东西,但一点指导将不胜感激。 (这是为了学校,不想作弊,只需要一些帮助)。

import java.util.Scanner;

public class Lab4
{
    public static void main(String[] args)
    {


    double large = 0;
    double small = 0;
    double even = 0;
    double odd = 0;
    double foot = 0;
    double ball = 0;
    double eagles = 0;
    System.out.println("Enter positive or negative integers -- enter zero to quit");
    Scanner scan = new Scanner(System.in);
    boolean philly = false;

    while (!philly)
    {
        eagles = scan.nextDouble();
        if (eagles == 0)
        {
            philly = true;
        }
        else
        {
            foot = foot + eagles;
            ball++;
        }
    }

    if (ball > 0)
    {
        System.out.println("The number of integers entered is: " + ball);
        double avg = foot / ball;
        System.out.println("Average of integers: " + avg);
    }
    else
    {
        System.out.println("No data");
        }


    }
}

3 个答案:

答案 0 :(得分:1)

跟踪最大值和最小值通常以这种方式完成:

  • 为max分配变量;将它设置为一个可笑的低数字(零,负等)。
  • 为min分配变量;将它设置为一个非常高的数字。
  • 在循环中,输入if(),如果current大于max
  • ,则将max设置为current
  • 类似if()for min to other way

奇数甚至只对整数有意义(即先转换为int或无符号)。使用模数运算符("奇数"表示var%1 == 1等)。

答案 1 :(得分:0)

对于奇数和偶数,请查看at this link

对于最高和最低数字,您需要检查新数字是否高于/低于先前的最高/最低

答案 2 :(得分:0)

根据要求提供更多细节。我已经尝试了下面代码的几种变体,但我的最大,最小,偶数和奇数整数都被打破了。

import java.util.Scanner;

public class Lab4
{
    public static void main(String[] args)
    {


    double large = Integer.MAX_VALUE;
    double small = Integer.MIN_VALUE;
    double evenCount = 0;
    double oddCount = 0;
    double foot = 0;
    double ball = 0;
    double eagles = 0;
    System.out.println("Enter positive or negative integers -- enter zero to quit");
    Scanner scan = new Scanner(System.in);
    boolean philly = false;

    while (!philly)
    {
        eagles = scan.nextDouble();
        if (eagles == 0)
        {
            philly = true;
        }
        else
        {
            foot = foot + eagles;
            ball++;
        }
    }

    if (eagles%2==0)
    {
        evenCount++;
        System.out.println("The number of even integers is: " + evenCount);

    if (eagles%2==1)
    oddCount++;
        System.out.println("The number of odd integers is: " + oddCount);

    if (eagles < small)
        small = eagles;
    System.out.println("The smallest integer entered is: " + small);

    if (eagles > large)
        large = eagles;
        System.out.println("The largest integer entered is: " + large);

    if (ball > 0)

        System.out.println("The number of integers entered is: " + ball);
        double avg = foot / ball;
        System.out.println("Average of integers: " + avg);
    }
    else
    {
        System.out.println("No data");
        }


    }
}