找到最小正面价值 [英] Find the Minimum Positive Value

查看:169
本文介绍了找到最小正面价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的算法来找到从固定数量的最小非零正值(在这种情况下,3)值或返回0,如果没有问题,正

What's the best algorithm to find the smallest non zero positive value from a fixed number (in this case 3) of values or return 0 if there are no positive questions?

我的幼稚的做法是低于(在Delphi中,但随时使用任何你喜欢的),但我认为还有一个更优雅的方式。

My naive approach is below (in Delp but feel free to use whatever you like), but I think there's a more elegant way.

value1Temp := MaxInt;
value2Temp := MaxInt;
value3Temp := MaxInt;

if ( value1T > 0) then
  value1Temp := value1;
if ( value2 > 0) then
  value2Temp := value2;
if ( value3 > 0) then
  value3Temp  := value3;

Result := Min(value1Temp, Min(value2Temp, value3Temp));
if Result = MaxInt then
  Result := 0;

编辑:不好意思添加什么需要,如果没有正数。我原本以为它在那里过,但一定是错过了。

Sorry added what's needed if there are no positive numbers. I thought I had it in there before, but must have missed it.

推荐答案

我会做这样的:

结果:= MAXINT;
  如果值1> 0,那么结果:= MIN(结果,值1);
  如果值2> 0,那么结果:= MIN(结果,值2);
  如果值3> 0,那么结果:= MIN(结果,数值3);
  如果结果= MAXINT那么结果:= 0;

Result := MaxInt;
if value1 > 0 then Result := min(Result, value1);
if value2 > 0 then Result := min(Result, value2);
if value3 > 0 then Result := min(Result, value3);
if Result = MaxInt then Result := 0;

如果你想让它在问题的任意数量的循环,那么:

If you want it in a loop with an arbitrary number of questions, then:

结果:= MAXINT;
  因为我:= 1到N做
       如果值[I]> 0,那么结果:= MIN(结果,值[I]);
  如果结果= MAXINT那么结果:= 0;

Result := MaxInt;
for I := 1 to N do
   if value[I] > 0 then Result := min(Result, value[I]);
if Result = MaxInt then Result := 0;

如果你想要的值数组是从零开始的,改变的循环是:0到N-1

If you want the value array to be zero-based, change the for loop to be: 0 to N-1

我觉得这$​​ C $ C非常清楚究竟正在做什么。

I think this code makes it very clear exactly what is being done.

把然后语句在同一行,使在这个简单的情况下,code看起来更整洁,但随时如果你觉得有必要缩进,那么语句到下一行。

Putting the "then" statements on the same line makes the code look cleaner in this simple case, but feel free to indent the "then" statements onto the next line if you feel it's necessary.

这篇关于找到最小正面价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆