创建带有限幅器的步进器控件
Creating a stepper control with a limiter
我创建了一个带有限制器的简单步进器控件。
总的来说,它似乎运作良好。但是如果我尝试使限制器的范围从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 个参数,它们是
- 最小限制值(也可以是最大值)
- 最大限制值(也可以是最小值)
- 初始值
- 步骤间隔
此外,构造函数只能接受 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()
,它包含真正的最小值。
相关文章:
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 需要反转音频步进公式
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 在编译时,C++项目抛出错误 C2228,这是预期的,因为控件在运行时未达到该点
- 如何更改窗体上所有控件的标题?[C++生成器]
- 双击更改 mfc 中列表控件中的行的颜色
- Arduino Nano:A4988 使用串行输入时通过定时器进行步进控制不稳定
- 派生的 wxPanel 控件如何访问其中包含 wxDialog 中的数据?
- 如何从代码本身向 wxwidgets 中的文本控件插入字符?
- 如何在MFC中的静态文本控件上插入图标?
- 我的主窗口在创建时或单击更新区域时是否会收到编辑控件?
- 如何在Qt C++中向自定义控件添加属性?
- C/C++ 检测双击 TVItem 的常用控件
- 从C++标头中导入常量而不是硬编码它们:扩展 .net 控件?
- 控件不会在选择函数旁边移动
- MFC:我们能否扩展CEditView中存在的CEdit控件类行为
- 通过嵌入式 IWebBrowser2 控件中的链接打开 youtube 搜索失败
- 锁定步进pthread互斥
- 创建带有限幅器的步进器控件
- c++ MFC 将编辑控件中的字符串转换为十六进制