使用 for 循环实现 max 的奇怪问题
我花了最后一个小时对这个问题进行反复试验,但没有成功。我们必须使用通用编码指南(例如 scan.nextDouble)而不是实际数字来找到特定数量的双精度值的最大值。唯一的问题是我们只能在某个点添加代码。 (其中 ... 是)
double value, valMax;
int n;
n = scan.nextInt();
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
...
}
其中读入的第一个值是 int,它是要输入的双精度数的数量。
这很困难,因为我必须找到一种方法在循环内初始化 valMax 而不搞乱其他任何东西。
这就是我一直在做的事情,但对我来说没有任何作用。
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
if(j == 0)
{
valMax = scan.nextDouble();
j++;
}
else
{
continue;
}
if(value >= valMax)
{
valMax = value;
}
}
输入示例:
5 -4.7 -9.2 -3.1 -8.6 -5.0
其中 -3.1 是最大值,5 是后续数字的计数。
I spend the last hour doing trial and error with this problem with no avail. We have to, using general coding guidelines (like scan.nextDouble) instead of actual numbers, find the max of a certain number of double values. The only catch is that we can only add code at a certain point. (where the ... is)
double value, valMax;
int n;
n = scan.nextInt();
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
...
}
Where the first value read in is an int and that is the amount of doubles to be entered.
It is difficult because I have to find a way to initialize valMax inside the loop without messing up anything else.
This is what I have been working with, but with nothing working for me.
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
if(j == 0)
{
valMax = scan.nextDouble();
j++;
}
else
{
continue;
}
if(value >= valMax)
{
valMax = value;
}
}
Example input:
5 -4.7 -9.2 -3.1 -8.6 -5.0
Where -3.1 is the max and 5 is the count of following numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码似乎是一个好的开始。
为了帮助解决您的问题,请考虑:
j++
?你真的需要它吗? (提示:否;-) )j>0
执行什么操作(即在第一次迭代之后)?这应该很快就会给你一个可行的解决方案。
Your code seems like a good start.
To help solve your problem, consider:
j++
? Do you really need it? (Hint: no ;-) )j>0
(i.e. after the first iteration)?That should quickly give you a working solution.
是否允许在循环之前设置
valMax
?因为在这种情况下,您可以通过进行正常的比较
value > 来忘记奇怪的事情。 valMax
。如果你不是,你的方法就是你应该做的事情,但有两件事:
j++
的增量,因为for
循环会自己关心它。else { continue; }
将使for
的主体跳转到下一个迭代,而不关心 continue 之后的代码。您确定这就是您想要做的吗?我认为您可以在第一次迭代(
j == 0
)时初始化为Double.MIN_VALUE
,然后正常运行:您唯一需要的是valMax
在第一次与值比较之前初始化,而不是在从标准输入扫描之前初始化。Are you allowed to set the
valMax
before the loop? Because in that case you can just doand just forget about strange things by doing a normal comparison
value > valMax
.If you are not your approach is how you should do but two things:
j++
since thefor
loop will care about it by itself..else { continue; }
will make the body of thefor
jump to next iteration without caring about code that is after the continue. Are you sure that is what you want to do?I think that you can initialize to
Double.MIN_VALUE
at first iteration (j == 0
) and just behave normally afterwards: the only thing you need is thatvalMax
is initialized before the first comparison with value, not before the scan from stdin..