【问题标题】:Creating a stepper control with a limiter [duplicate]使用限制器创建步进控制 [重复]
【发布时间】:2017-07-15 13:10:13
【问题描述】:

我创建了一个带有限制器的简单步进控件。

总的来说,它似乎运作良好。但是如果我尝试使限制器的范围从numeric_limits<float>::min()numeric_limits<float>::max(),当值变为负时它就不能正常工作。

这是我的完整测试代码。

#include <iostream>

using namespace std;

class Stepper {

public:

    Stepper(float from, float to, float value, float interval){ //limited range

        mFrom = from;
        mTo = to;
        mValue = value;
        mInterval = interval;
    }
    Stepper(float value, float interval){ //limitless range version

        mFrom = numeric_limits<float>::min();
        mTo = numeric_limits<float>::max();
        mValue = value;
        mInterval = interval;
    }

    float getCurrentValue() {

        return mValue;
    }
    float getDecreasedValue() {

        if (mFrom < mTo)
            mValue -= mInterval;
        else
            mValue += mInterval;

        mValue = clamp(mValue, min(mFrom, mTo), max(mFrom, mTo));
        return mValue;
    }
    float getIncreasedValue() {

        if (mFrom < mTo)
            mValue += mInterval;
        else
            mValue -= mInterval;

        mValue = clamp(mValue, min(mFrom, mTo), max(mFrom, mTo));
        return mValue;
    }

private:

    float clamp(float value, float min, float max) {
        return value < min ? min : value > max ? max : value;
    }
    float mFrom, mTo, mValue, mInterval;
};

int main(int argc, const char * argv[]) {

    bool shouldQuit = false;

//    Stepper stepper(-3, 3, 0, 1); //this works

    Stepper stepper(0, 1); //this doesn't work when the value becomes negative


    cout << "step : " << stepper.getCurrentValue() << endl;

    while (!shouldQuit) {

        string inputStr;
        cin >> inputStr;

        if (inputStr == "-") //type in '-' decrease the step
            cout << "step : " << stepper.getDecreasedValue() << endl;
        else if (inputStr == "+") //type in '+' increase the step
            cout << "step : " << stepper.getIncreasedValue() << endl;
        else if (inputStr == "quit")
            shouldQuit = true;
    }
    return 0;
}

我的类构造函数需要 4 个参数

  1. 最小限制值(这也可以是最大值)
  2. 最大限制值(这也可以是最小值)
  3. 初始值
  4. 步骤间隔

另外,构造函数只能接受两个参数

  1. 初始值
  2. 步骤间隔

这种情况下,限制器的范围从numeric_limits&lt;float&gt;::min()numeric_limits&lt;float&gt;::max()

但在这种情况下,如果该值变为负数,则返回1.17549e-38,它与numeric_limits&lt;float&gt;::min() 的值相同。

可以解决这个问题吗? 任何建议或指导将不胜感激!

【问题讨论】:

    标签: c++ stepper


    【解决方案1】:

    std::numeric_limits&lt;float&gt;::lowest() 是数学意义上的最低值。 std::numeric_limits&lt;float&gt;::min() 只是最小的正值(大于零)。

    详情请见this question。命名可追溯到 C。

    【讨论】:

    • 这真的很有帮助。非常感谢!
    【解决方案2】:

    在我看来,min() 有一个不幸的名字。它的值是最小的、正的、标准化的浮点数。

    改用lowest(),它包含真正的最小值。

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      相关资源
      最近更新 更多