C++ 中给定值的第一个最小值
string result;
double zpls, zmin, ypls, ymin, xpls, zmin ;
zpls = 4.2;
zmin = 0;
ypls = -2;
ymin = 4.2;
xpls = 6;
xmin = 8;
如何在这些值中找到“第一个最小正数”并设置
result = "+Z";// or wichever value is lowest -z, +Y etc
(在C++中)
我尝试了数组,如果其他和 min(zpls,min(zmin,min(....))) // 使用 #include
但无法正确获取,
谢谢
string result;
double zpls, zmin, ypls, ymin, xpls, zmin ;
zpls = 4.2;
zmin = 0;
ypls = -2;
ymin = 4.2;
xpls = 6;
xmin = 8;
How to find "first minimum positive" among these values and set
result = "+Z";// or wichever value is lowest -z, +Y etc
(in C++)
i tried arrays , if else and
min(zpls,min(zmin,min(....))) // with #include <algorithm>
but could not get it correctly
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只要您拥有自变量中的数据,您就需要
按照该模式执行 if-else 等操作。最后的
result
要么包含您想要的字符串,要么为空(在这种情况下,没有正值。)这是一个完整的示例:
As long as you have the data in independent variables, you'll need to do an if-else
and so forth, in that pattern. At the end
result
will either have the string you want, or it will be empty (in which case, there were no positive values.)Here is a complete sample:
如果您在任何集合上运行
std::sort
数字,“第一个最小正值”将只是“第一个正值”。如果您在该排序集合上运行
std::find_if
,你可以找到第一个正数。if you run
std::sort
on any collection of numbers, the "first minimum positive" will simply be the "first positive".If you run
std::find_if
on that sorted collection, you can find that first positive.您真的需要单独的变量吗?为什么不这样设计:
并插入
zmin = -3;
你会得到values[ZMinus] = -3;
然后你可以在
values
数组中找到最小索引并返回名称[minimumIndex];
are you really need sepearte variables. Why not to design like this:
and insted of
zmin = -3;
you getvalues[ZMinus] = -3;
then you can find minimum index in
values
array andreturn names[minimumIndex];
不要调整算法。该算法很清晰(“找到最小值”)。相反,调整搜索条件,并保持在 O(n) 范围内。
代码。
输出。
解释。
我们的排序函数是用
cmp
编码的。它检查其操作数的符号。如果两者均为负数,则较大者获胜。如果只有 LHS 为负,则在排序时自动优先选择 RHS。相反,如果 RHS 为负,则首选 LHS。两者都是积极的,我们回到正常秩序。好的一点是,它在范围内运行一次,时间复杂度为 O(n)。
Don't adjust algorithms. The algorithm is clear ("find minimum"). Adjust the search criteria instead, and stay in O(n) realm.
Code.
Output.
Explanation.
Our sorting function is encoded in
cmp
. It checks the signs of its operands. If both are negative, the bigger one wins. If only the LHS is negative, then RHS is automatically preferred in the sorting. On the opposite, if the RHS is negative, LHS is preferred. Of both are positive, we fall back to the normal order.Nice thing is that this runs exactly one time over the range and in O(n).