How to divide a float into two integers in C

Below I try to set the format specifier, but I want to do it differently every time I call the function. The point is to print a float Data_Ave. In one instance, I want the% 2.3f specifier, and so I will pass the function a 2 for sig_figs_before and 3 for sig_figs_after. In the following case, I want% 1.4f, so I would pass these ints.

char * Send_Data(float Data[10], const char* SUBJECT_SEND_NAME, char *Data_Backup, int sig_figs_before, int sig_figs_after)
{
  float Data_Ave = ((Data[0] + Data[1] + Data[2] + Data[3] + Data[4] +
            Data[5] + Data[6] + Data[7] + Data[8] + Data[9])/10);
  sprintf(msgBody,"%%i.%if, ", before_decimal, after_decimal, Data_Ave);
  ... //Some more code
  }

I'm sure this will not work, so I decided to split the float into two ints and print them like this:

sprintf(msgBody,"%i.%i, ", int_value, decimal_value);

But I do not know how to split the float correctly. Any suggestions?

+4
source share
3 answers

Do you want to:

sprintf(msgBody,"%*.*f, ", before_decimal+after_decimal+1, after_decimal, Data_Ave);

, * . , %N.Mf, N - ( , , , , ..), M - . before_decimal+after_decimal+1 not before_decimal.

+5

sprintf - , .

sprintf(format, "%%%i.%if", before_decimal, after_decimal);
sprintf(msgBody, format, Data_Ave);

, . ( 2 3) %2.3f format; msgBody.

snprintf sprintf, , - !

+2

sprintf() " ".

, sig_figs_before, sig_figs_after .

char * Send_Data(float Data[10], const char* SUBJECT_SEND_NAME, 
    char *Data_Backup, int sig_figs_before, int sig_figs_after) {

  assert(sig_figs_before >= 1);
  assert(sig_figs_after >= 0);

  float Data_Ave = ((Data[0] + Data[1] + Data[2] + Data[3] + Data[4] +
                     Data[5] + Data[6] + Data[7] + Data[8] + Data[9])/10);

  int width = sig_figs_before + 1 + sig_figs_after;  // +1 for '.'
  // Make room for '-'
  if (Data_Ave < 0) width++;
  sprintf(msgBody, "%#*.*f, ", width, sig_figs_after, Data_Ave);
}

'#' sig_figs_after == 0 .

: sig_figs_before Data_Ave . @Matt Patenaude snprintf() .

:

if (log10(fabs(Data_Ave)+0.5) > sig_figs_before) UseAlternativePrint();   
0

Source: https://habr.com/ru/post/1529531/


All Articles