创建带有限幅器的步进器控件

Creating a stepper control with a limiter

本文关键字:控件 步进 创建      更新时间:2023-10-16

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

总的来说,它似乎运作良好。但是如果我尝试使限制器的范围从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. 步骤间隔

此外,构造函数只能接受 2 个参数,即

  1. 初始值
  2. 步骤间隔

在这种情况下,限幅器的范围从numeric_limits<float>::min()numeric_limits<float>::max().

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

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

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

有关详细信息,请参阅此问题。命名可以追溯到 C。

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

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