未正确评估'If'条件

'If' condition not correctly evaluated

本文关键字:If 条件 评估      更新时间:2023-10-16

从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或类似的东西。