查找最小数字,该数字不为零

Finding the lowest number, which isn't zero

本文关键字:数字 小数 查找      更新时间:2023-10-16

我有三个称为a、b、c的整数,需要找到它们中的最低数,而不是0。但同时,它应该能够处理所有三个数字都为0的特殊情况。

这必须在C或C++14 中实现

示例1:

a = 4;
b = 0;
c = 1;
Result = c

示例2

a = 0;
b = 0;
c = 0;
Result = Special case

示例3

a = 11;
b = 46;
c = 15;
Result = a

到目前为止,我还没能找到一种在c或c++中实现这一点的优雅方法。

我考虑过把它放在一个排序的数组中,并不断弹出数字,直到它得到除零之外的值。但这似乎是一种过于复杂的方法

编辑

忘了提一下,我试图找到的价值观从来都不是消极的,而是积极的。

删除了代码,因为它不应该是代码审查

如果只有三个值,使用简单的if语句可能是一个解决方案。

那么逻辑可以是(伪代码(

if (a is larger than zero) and (b is larger than zero and a is smaller than b) and (c is larger than zero and a is smaller than c)
a is the smallest
else if (b is larger than zero) and (c is larger than zero and b is smaller than c)
b is the smallest
else if c is larger than zero
c is the smallest
else
all are either zero or negative

请注意,每个if检查都会逐渐变小。这是因为前面的条件删除了一个不需要进一步检查的选项。

这当然适用于较大的变量链,只要变量的数量是固定的。不过,它很快就会变得笨拙,所以对于超过三四个变量,应该使用其他方法。

大部分控制流可能如下所示:

#include <iostream>

int find_smallest_nonzero(int a, int b, int c)
{
if (a > 0 || b > 0 || c > 0) {
if ((b >= a || b == 0) && (c >= a || c == 0) && (a > 0))
return a;
else if ((c >= b || c == 0) && (b != 0))
return b;
else
return c;
} else return -1;
}
int main() {
std::cout 
// permutations
<< find_smallest_nonzero(1, 2, 3) << ' '
<< find_smallest_nonzero(2, 1, 3) << ' '
<< find_smallest_nonzero(2, 3, 1) << ' '
// one zeros
<< find_smallest_nonzero(1, 0, 3) << ' '
<< find_smallest_nonzero(0, 1, 3) << ' '
<< find_smallest_nonzero(1, 3, 0) << ' '
// two zeros
<< find_smallest_nonzero(1, 0, 0) << ' '
<< find_smallest_nonzero(0, 1, 0) << ' '
<< find_smallest_nonzero(0, 0, 1) << ' '
// duplicates
<< find_smallest_nonzero(2, 2, 1) << ' '
<< find_smallest_nonzero(2, 1, 2) << ' '
<< find_smallest_nonzero(1, 2, 2) << ' '
<< find_smallest_nonzero(1, 1, 2) << ' '
<< find_smallest_nonzero(1, 2, 1) << ' '
<< find_smallest_nonzero(2, 1, 1) << ' '
// all zeros
<< find_smallest_nonzero(0, 0, 0) << 'n';
}
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1

它将返回abc中的最小非零值,除非它们都是0,在这种情况下返回-1

也许有更快的方法。

int lowest(int a, int b, int c) {
auto v = {a, b, c};
return *std::min_element(std::begin(v), std::end(v), [](int x, int y) {
return (x < y && x != 0) || y == 0;
});
}

这种方法可以处理任意数量的元素。在特殊情况下,函数只返回零(不需要使用不同的特殊值(。

您可以在C++中使用std::min 执行以下操作

int a = 0,b = 0,c = 0;
int x = std::min( { a,b,c },
[](const auto& n1, const auto& n2) {
if (not n1)
return false;
if (not n2)
return true;
return n1 < n2;
});
std::string out = x?std::to_string(x):std::string{"Special Case"};
if(a==0 && b==0 && c==0){
return "Special case"
}else{
// now put each equals zero and compare the other, last else compare all three
}

您可以编写一个函数打印输出。