我的程序在哪里拉随机数?

时间:2017-03-23 18:14:38

标签: java arrays loops

我正在对codingame.com进行挑战,找到最接近零的整数(正或负)。我写的代码适用于SIX挑战中的四个。另外两个,我在输入之外得到完全出乎意料的输出。

bin/osm3s_query < my_query > my_query_result

This is the output, with debugging, of my code

1 个答案:

答案 0 :(得分:0)

我不认为你的for循环正在做你想做的事情。就像一样。

temps[i] = in.nextInt();  // This is sensible enough
closest = Math.abs(temps[0]); // Every time your loop runs, the closest value to 0 is... the absolute value of the first int in the array?
//System.err.println(temps[i]);
if (closest > 0)  // This is only false if closest is 0
    {
        if (closest > i) // This makes the outer if redundant, since i >= 0. It's also not clear what the point of this condition even is
        {
           closest = i; // Here's the big one: you're setting closest to your iterator, the index of the current number in the array instead of the number itself. 
        }
     }
       else if (closest < 0) // This is never true, since absolute values are always >=0
       {
         if (closest < i)
         {
             closest = i;
         }
       }
    }

通过你的代码,一次一行,跟踪每个变量的值,你将能够找到你得到的数字来自哪里以及你所做的事情是否有意义

看起来你在那里的某个地方有大部分正确的东西,但它们并没有正确地组合在一起。当您修改算法时,不要忘记您的目标:您希望在列表中找到绝对值最小的数字。您可以通过检查下一个数字的绝对值是否小于当前最小值来执行此操作。

相关问题