Using floats with sprintf() in embedded C

后端 未结 13 1846
别跟我提以往
别跟我提以往 2020-12-24 06:35

Guys, I want to know if float variables can be used in sprintf() function.

Like, if we write:

sprintf(str,\"adc_read = %d \         


        
13条回答
  •  伪装坚强ぢ
    2020-12-24 06:58

    Similar to paxdiablo above. This code, inserted in a wider app, works fine with STM32 NUCLEO-F446RE.

    #include 
    #include 
    #include 
    void IntegFract(char *pcIntegStr, char *pcFractStr, double dbValue, int iPrecis);
    
    main()
    {
       char acIntegStr[9], acFractStr[9], char counter_buff[30];
       double seconds_passed = 123.0567;
       IntegFract(acIntegStr, acFractStr, seconds_passed, 3);
       sprintf(counter_buff, "Time: %s.%s Sec", acIntegStr, acFractStr);
    }
    
    void IntegFract(char *pcIntegStr, char *pcFractStr, double dbValue, int 
    iPrecis)
    {
        int iIntegValue = dbValue;
        int iFractValue = (dbValue - iIntegValue) * pow(10, iPrecis);
        itoa(iIntegValue, pcIntegStr, 10);
        itoa(iFractValue, pcFractStr, 10);
        size_t length = strlen(pcFractStr);
        char acTemp[9] = "";
        while (length < iPrecis)
        {
            strcat(acTemp, "0");
            length++;
        }
        strcat(acTemp, pcFractStr);
        strcpy(pcFractStr, acTemp);
    }
    

    counter_buff would contain 123.056 .

提交回复
热议问题