This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

[参考译文] TM4C1294NCPDT:TM4C1294NCPDT:使用 UARTLprintf 打印浮点数

Guru**** 2611705 points


请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

https://e2e.ti.com/support/microcontrollers/arm-based-microcontrollers-group/arm-based-microcontrollers/f/arm-based-microcontrollers-forum/1129768/tm4c1294ncpdt-tm4c1294ncpdt-printing-float-numbers-using-uartprinf

器件型号:TM4C1294NCPDT

我正在使用其他帖子中共享的建议代码 来打印浮点数、将其拆分为整数部分和小数部分:

void FloatTo2PartInteger(float IntegerToConvert, int32_t* IntegerPart, int32_t* FractionPart){

    *IntegerPart = (int32_t) IntegerToConvert;                   // Convert IntegerPart from float number
    *FractionPart = (int32_t) (IntegerToConvert * 10.0f);        // Convert FractionPart from float number
    *FractionPart = *FractionPart - (*IntegerPart)*10;             // Remove IntegerPart from FractionPart

    if (*FractionPart < 0) {                                             // If FractionPart is negative
        *FractionPart *= -1;                                             // Multiply itself per -1 to obtain positive part
    }

}

但我发现它不会为[-1...范围内的数字打印负信号。 0 ]。 示例:当我尝试打印数字-0.063时、我具有没有负信号的0.063。  

以下是修复它的建议代码:

void PrintFloat(float finput, uint8_t *ui8Sign, int32_t *i32IntegerPart, int32_t *i32FractionPart) {
    //
    // Convert the floating point input to an integer part
    // and fraction part for easy printing.
    //
    *i32IntegerPart = (int32_t)finput;
    *i32FractionPart = (int32_t)(finput * 1000.0f);
    *i32FractionPart = *i32FractionPart - (*i32IntegerPart * 1000);
    if(*i32FractionPart < 0) {
        *i32FractionPart *= -1;
        if(*i32IntegerPart == 0) {
            *ui8Sign = 0x2D;
        }
    }
    else {
        *ui8Sign = 0x00;
    }
}

 下面是一个使用示例:

    PrintFloat(fADISData[3], &ui8Sign, &i32IntegerPart, &i32FractionPart);
    UARTprintf("X_ACCEL: %c%d.%03d ", ui8Sign, i32IntegerPart, i32FractionPart);

我认为问题是、当整数部分为零时、无法保存符号信息。

  • 请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

    您好 Richard、

     感谢您为解决方法提供代码片段。 我将为您的帖子添加书签以供参考、因为这将使遇到相同问题的其他人受益-打印负浮动值。