import java.util.*;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int c=5526;
int inp;
for(int a=0;a<n;a )
{
inp=sc.nextInt();
if(Math.abs(inp)<c)
{
c=inp;
}
}
System.out.print(c);
}
}
Input:
Error:
idk what the problem is, i cant try anything cuz idek where the bug is.
CodePudding user response:
We want to display the temperature closest to 0
, i.e. the temperature whose absolute value is smallest. The code presented is already pretty close. There is just one small bug in this line:
if (Math.abs(inp) < c)
We compare the absolute value of inp
against the value of c
. Looking at the body of the if
, we see that c
is set to the value of inp
. The value of inp
can be negative, thus c
can be negative. Going back to the if
-condition: as soon as c
is negative, Math.abs(inp) < c
will always evaluate to false
. Hence, we have to also take the absolute value of c
in the condition:
if (Math.abs(inp) < Math.abs(c))
This will produce the expected output.
CodePudding user response:
The question is not asked properly but nevertheless, I will try to answer according to my best understanding. So the problem is when you run the program you are entering input in the wrong way for example you enter the number of temperatures that will be compared and then add the temperatures one after the other which in this case it is not accepted as a valid number instead it should be followed by Enter. Also, your code is not producing the correct result you have a logic error.