未正确评估'If'条件
'If' condition not correctly evaluated
从shell接收(0,8(间隔中的整数值,i cin
到数组的 uint8_t
元素,执行以下操作:
char answer;
do
{
// Instructions
std::cout << "Linear actuator resolution is:n"
<< "u0394x = u03B1r/2^i, with u03B1 = " << std::to_string(ALPHA)
<< " degrees, r = " << std::to_string(pulleyR) << " m and i in [0 : 8]n";
// Parameter selection
std::cout << "Please enter a valid value for param 'i': ";
std::cin >> Engines_uSteppingLevel[RAIL];
if(Engines_uSteppingLevel[RAIL] > (RES_LEVELS - 1))
// Wrong selection, repeat question
std::cout << 'r';
else
{
// Print out the selected resolution and ask user to confirm or restart selection
std::cout << "Selected linear resolution: " << std::fixed << std::setprecision(4)
<< ALPHA*pulleyR/(1<<Engines_uSteppingLevel[RAIL])
<< "m, enter 'y' to confirm, any other key to change selection ";
std::cin >> answer;
if(answer == 'y')
break;
}
}while(true);
即使我输入正确的值,循环也不会破裂。
输入:
std::cout << Engines_uSteppingLevel[RAIL] << ' ' << (RES_LEVELS - 1) << 'n';
代替:
std::cout << 'r';
外壳输出是:
Please enter a valid value for param 'i': 0
0 8
Please enter a valid value for param 'i': 3
3 8
这是没有意义的。
您在这里遇到的问题是C 处理UINT8_T类型的方式:它认为这是一个char。如果将调试输出语句更改为:
std::cout << static_cast<int>(Engines_uSteppingLevel[RAIL]) << ' ' << (RES_LEVELS - 1) << 'n';
您会看到,当您键入A'0',而ASCII'0'存储在您的UINT8_T变量中,该变量具有48。同样,当您键入'3'时,您存储了51个,等等。
最简单的解决方案将是使用字符转换,例如:
Engines_uSteppingLevel[RAIL] -= '0';
请注意,此解决方案仅适用于单位数值。一个更健壮,可扩展的解决方案将涉及一个std :: string或char缓冲区,然后呼叫atoi,strtoul,std :: stoul或类似的东西。
相关文章:
- 将按位if条件转换为普通if条件
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么这个if(s[j]==s[i] && i>0)条件不适用于这个[{()}]
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 当我的 if 条件计算结果为 false 时,我的 else 块将不会执行
- 使用枚举作为条件,if 条件将返回什么,真或假?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 使用 if 条件对数字进行分组
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 在if条件下,右或左改变值的相等性检查是否有任何区别
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- 将子字符串与字符串数组进行比较的 IF 条件会在C++中产生错误
- 在 constexpr-if 条件下比较 constexpr 函数参数会导致错误
- 带有逻辑 OR 运算符的 if 条件的缩写?
- 为什么我可以将 ifstream 文件置于 if 条件?
- 如何将特征张量的值作为'if'条件表达式
- 在 c++ 中检查 if 条件中的向量位置范围
- 如何在Char数组中搜索Char在IF条件语句中
- 未正确评估'If'条件