gpt4 book ai didi

c++ - 找到最小的数字,它不为零

转载 作者:行者123 更新时间:2023-11-30 03:13:29 29 4
gpt4 key购买 nike

我有三个名为 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 检查都会逐渐变小。这是因为前面的条件删除了不需要进一步检查的备选方案。

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

关于c++ - 找到最小的数字,它不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642858/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com