get closest value to a number in array

后端 未结 12 1799
庸人自扰
庸人自扰 2020-12-01 07:52

I have an array of positive/negative ints

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers         


        
12条回答
  •  Happy的楠姐
    2020-12-01 08:35

    I did this as an assignment for my course, and I programmed it in Ready to Program Java, so sorry if its a bit confusing.

    // The "Ass_1_B_3" class.
    import java.awt.*;
    import hsa.Console;
    
    public class Ass_1_B_3
    {
        static Console c;           // The output console
    
        public static void main (String[] args)
        {
            c = new Console ();
    
            int [] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};
            int nearZero = 0;
            int temp = 0;
            int temp2 = data[0];
    
            for (int i = 0; i < data.length; i++)
            {
                temp = Math.abs (data[i]);
                nearZero = temp2;   
                if (temp < temp2)
                {
                    temp2 = temp;
                    nearZero = data[i];
                }
    
    
            }
    
            c.println ("The number closest to zero is: " + nearZero);
    
            // Place your program here.  'c' is the output console
        } // main method
    } // Ass_1_B_3 class
    

提交回复
热议问题