Because I was coding this project for fun, I got stuck in getting the output that I want: positive Getting the element 2 and -2 of the input
To keep it simple, I want the output to be positive 2 negative negative 2.
The general idea of this is zero The closest element for is happening. But here, I'm assuming that the positive one is closer to 0.
Hope anyone of you can answer my question. Personally, I want to be better on Java so that I can help a newbie like myself, later in the future. Anyway, thanks, in advance
Fixed int getClosestToZero (int [] array) {int num = array [0]; Int absNum = Math.abs (num); For (int i = 1; i & lt; array.label; ++ i) {int newAbs = Math.abs (array [i]); If (newAbs & lt; absNum) {absNum = newAbs; Num = array [i]; }} Return number; } Public static zero main (string [] args) {int [] myArray = {-2, 2}; Println (getClosestToZero (myArray)); }
This should work:
Fixed Int GetClosestToZero (int [] array) {int num = array [0]; Int absNum = Math.abs (num); For (int i = 1; i & lt; array.label; ++ i) {int newAbs = Math.abs (array [i]); If (newAbs & lt; absNum) {absNum = newAbs; Num = array [i]; } Else if (newAbs == absNum & array [i]> = 0) // If it is equal and current is positive, then take it {num = array [i]; }} Return number; }
Comments
Post a Comment