source

printf()에서 0 뒤에 오는 것을 피합니다.

nicesource 2022. 11. 15. 21:39
반응형

printf()에서 0 뒤에 오는 것을 피합니다.

printf() 함수 패밀리의 포맷 지정자에 자꾸 문제가 생깁니다.제가 원하는 것은 소수점 뒤에 최대 자리수를 가진 두 자리(또는 부동)를 인쇄할 수 있는 것입니다.사용하는 경우:

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

나는 이해한다

359.013
359.010

원하는 대신

359.013
359.01

누가 나 좀 도와줄래?

후행 0을 제거하려면 "%g" 형식을 사용해야 합니다.

float num = 1.33;
printf("%g", num); //output: 1.33

질문이 조금 명확해진 후 0을 억제하는 것만이 아니라 출력을 소수점 이하 3자리까지 제한하는 것도 요구되었습니다.나는 그것이 sprintf 형식 문자열만으로는 불가능하다고 생각한다.팍스 디아블로가 지적했듯이, 끈 조작이 필요할 것이다.

으로 할 수 이 아닙니다.printf은 다음과 같습니다가장 가까운 곳은 다음과 같습니다.

printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01);  // 359.01

단, ".6"은 총 숫자 폭이기 때문에

printf("%.6g", 3.01357); // 3.01357

깨트려버려요.

수 있는 건sprintf("%.20g")문자열 버퍼에 대한 숫자를 지정한 후 소수점 이후의 N자만 포함하도록 문자열을 조작합니다.

num에 하면, 는 첫 한 모든 을 제거합니다.N소수점 이하에서는 후행 제로(모두 제로인 경우는 소수점)를 삭제합니다.

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);
:    :
void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p == '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

부분이 에 들지 않으면 부분이 에 들지 않는 ),0.123990.123하지 0.124에서 이미 하고 있는 할 수 있습니다.printf사전에 숫자를 분석하여 폭을 동적으로 작성한 후 이를 사용하여 숫자를 문자열로 변환하면 됩니다.

#include <stdio.h>

void nDecimals (char *s, double d, int n) {
    int sz; double d2;

    // Allow for negative.

    d2 = (d >= 0) ? d : -d;
    sz = (d >= 0) ? 0 : 1;

    // Add one for each whole digit (0.xx special case).

    if (d2 < 1) sz++;
    while (d2 >= 1) { d2 /= 10.0; sz++; }

    // Adjust for decimal point and fractionals.

    sz += 1 + n;

    // Create format string then use it.

    sprintf (s, "%*.*f", sz, n, d);
}

int main (void) {
    char str[50];
    double num[] = { 40, 359.01335, -359.00999,
        359.01, 3.01357, 0.111111111, 1.1223344 };
    for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
        nDecimals (str, num[i], 3);
        printf ("%30.20f -> %s\n", num[i], str);
    }
    return 0;
}

nDecimals()이 경우 필드 너비를 올바르게 계산한 후 이를 기반으로 한 형식 문자열을 사용하여 숫자 형식을 지정합니다. 하니스 ★★★★★★★★★★★★★★★★★★★★★」main()의 예를 나타냅니다.

  40.00000000000000000000 -> 40.000
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
 359.00999999999999090505 -> 359.010
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

한 번 .morphNumericString()'0'은 다음과 같습니다.

nDecimals (str, num[i], 3);

다음과 같이 입력합니다.

nDecimals (str, num[i], 3);
morphNumericString (str, 3);

콜링(calling))morphNumericStringnDecimals이 두 으로 합칠 수 거예요. 그러면 됩니다

  40.00000000000000000000 -> 40
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
 359.00999999999999090505 -> 359.01
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

왜 그냥 이렇게 하지 않는 거죠?

double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);

R.의 답변이 마음에 드네요.

float f = 1234.56789;
printf("%d.%.0f", f, 1000*(f-(int)f));

'1000'은 정밀도를 결정합니다.

0.5 반올림을 합니다.

편집

네, 이 답변은 몇 번 편집되어 몇 년 전에 제가 무슨 생각을 하고 있었는지 알 수 없었습니다(원래는 모든 기준을 충족하지 못했습니다).여기 새로운 버전이 있습니다(모든 기준을 충족하고 음수를 올바르게 처리함).

double f = 1234.05678900;
char s[100]; 
int decimals = 10;

sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);

테스트 케이스:

#import <stdio.h>
#import <stdlib.h>
#import <math.h>

int main(void){

    double f = 1234.05678900;
    char s[100];
    int decimals;

    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf("10 decimals: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" 3 decimals: %d%s\n", (int)f, s+1);

    f = -f;
    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative 10: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative  3: %d%s\n", (int)f, s+1);

    decimals = 2;
    f = 1.012;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" additional : %d%s\n", (int)f, s+1);

    return 0;
}

테스트 결과는 다음과 같습니다.

 10 decimals: 1234.056789
  3 decimals: 1234.057
 negative 10: -1234.056789
 negative  3: -1234.057
 additional : 1.01

이것으로 모든 조건이 충족되었습니다.

  • 0 뒤에 있는 최대 소수점 수가 고정되어 있습니다.
  • 후행 제로 삭제
  • 그것은 수학적으로 옳다(그렇지?)
  • 첫 번째 소수점이 0일 때도 (지금) 동작합니다.

도 이 은 두 입니다.sprintf는 문자열을 반환하지 않습니다.

내 생각은 주어진 두 배 값에 대해 0이 뒤따르지 않는 필수 정밀도를 계산하고 그것을 에 전달하는 것입니다."%1.*f" inprintf().printf this this this this this this 할 수 .이는 원라이너로도 가능합니다.

int main() {
    double r=1234.56789;
    int precision=3;
    printf(L"%1.*f", prec(r, precision), r);
}

int prec(const double& r, int precision)
{
    double rPos = (r < 0)? -r : r;
    double nkd = fmod(rPos, 1.0); // 0..0.99999999
    int i, ex10 = 1;
    for (i = 0; i < precision; ++i)
        ex10 *= 10;
    int nki = (int)(nkd * ex10 + 0.5);

    // "Eliminate" trailing zeroes
    int requiredPrecision = precision;
    for (; requiredPrecision && !(nki % 10); )  {
        --requiredPrecision;
        nki /= 10;
    }
    return requiredPrecision;        
}

여기 또 요.%g루션 ""(에 불과함 정밀도를 해야 합니다.항상 "충분히 넓은" 형식 정밀도(기본값은 6만)를 제공하고 값을 반올림해야 합니다.을 사용법

double round(const double &value, const double& rounding)  {
    return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;
}

printf("%.12g" round(val, 0.001)); // prints up to 3 relevant digits

이 높은 중 몇 가지는, 「중요한 방법」을 .%g 「」printf은 틀렸습니다. 것은잘잘 where where where where where where where where where where where where 라는 경우가 있기 때문입니다.왜냐하면%g과학적 표기법을 만들 것입니다.다른 솔루션에서는 원하는 소수 자릿수를 인쇄하기 위해 수학을 사용합니다.

은 '어느 정도'를 사용하는 합니다.sprintf%f변환 지정자 및 결과에서 후행 0 및 소수점을 수동으로 제거합니다.C99를 사용하다

#include <stdio.h>
#include <stdlib.h>

char*
format_double(double d) {
    int size = snprintf(NULL, 0, "%.3f", d);
    char *str = malloc(size + 1);
    snprintf(str, size + 1, "%.3f", d);

    for (int i = size - 1, end = size; i >= 0; i--) {
        if (str[i] == '0') {
            if (end == i + 1) {
                end = i;
            }
        }
        else if (str[i] == '.') {
            if (end == i + 1) {
                end = i;
            }
            str[end] = '\0';
            break;
        }
    }

    return str;
}

숫자와 소수 구분자로 사용되는 문자는 현재 로케일에 따라 달라집니다.위의 코드는 C 또는 미국 영어 로케일을 전제로 하고 있습니다.

f 앞에 있는 ".3"으로 인해 코드는 소수점 세 자리로 반올림됩니다.

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

따라서 두 번째 선을 소수점 이하 두 자리로 반올림할 경우 다음과 같이 변경해야 합니다.

printf("%1.3f", 359.01335);
printf("%1.2f", 359.00999);

이 코드는 원하는 결과를 출력합니다.

359.013
359.01

*이미 다른 행에 인쇄하고 있는 것을 전제로 하고 있습니다.그렇지 않은 경우는, 다음의 순서에 의해 같은 행에 인쇄되지 않게 됩니다.

printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);

다음 프로그램 소스코드가 이 답변에 대한 테스트였습니다.

#include <cstdio>

int main()
{

    printf("%1.3f\n", 359.01335);
    printf("%1.2f\n", 359.00999);

    while (true){}

    return 0;

}

게시된 해결책 중 일부에서 문제를 발견했습니다.위의 답변을 바탕으로 정리했습니다.나한테는 효과가 있는 것 같아.

int doubleEquals(double i, double j) {
    return (fabs(i - j) < 0.000001);
}

void printTruncatedDouble(double dd, int max_len) {
    char str[50];
    int match = 0;
    for ( int ii = 0; ii < max_len; ii++ ) {
        if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {
            sprintf (str,"%f", round(dd*pow(10,ii))/pow(10,ii));
            match = 1;
            break;
        }
    }
    if ( match != 1 ) {
        sprintf (str,"%f", round(dd*pow(10,max_len))/pow(10,max_len));
    }
    char *pp;
    int count;
    pp = strchr (str,'.');
    if (pp != NULL) {
        count = max_len;
        while (count >= 0) {
             count--;
             if (*pp == '\0')
                 break;
             pp++;
        }
        *pp-- = '\0';
        while (*pp == '0')
            *pp-- = '\0';
        if (*pp == '.') {
            *pp = '\0';
        }
    }
    printf ("%s\n", str);
}

int main(int argc, char **argv)
{
    printTruncatedDouble( -1.999, 2 ); // prints -2
    printTruncatedDouble( -1.006, 2 ); // prints -1.01
    printTruncatedDouble( -1.005, 2 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)
    printTruncatedDouble( 1.006, 2 ); // prints 1.01
    printTruncatedDouble( 1.999, 2 ); // prints 2
    printf("\n");
    printTruncatedDouble( -1.999, 3 ); // prints -1.999
    printTruncatedDouble( -1.001, 3 ); // prints -1.001
    printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)
    printTruncatedDouble( -1.0004, 3 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.0004, 3 ); // prints 1
    printTruncatedDouble( 1.0005, 3 ); // prints 1.001
    printTruncatedDouble( 1.001, 3 ); // prints 1.001
    printTruncatedDouble( 1.999, 3 ); // prints 1.999
    printf("\n");
    exit(0);
}

간단한 솔루션이지만 작업을 완료하고 알려진 길이와 정밀도를 할당하여 지수 형식을 사용할 가능성을 방지합니다(%g 사용 시 위험).

// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
    return (fabs(i - j) < 0.000001);
}

void PrintMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%.2f", d);
    else
        printf("%.3f", d);
}

최대 소수점 2자리, 소수점 4자리 등을 원하는 경우 "eles"를 추가하거나 제거합니다.

예를 들어 소수점 2개를 원하는 경우:

void PrintMaxTwoDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else
        printf("%.2f", d);
}

필드를 정렬 상태로 유지할 최소 너비를 지정하려면 다음과 같이 필요에 따라 증분합니다.

void PrintAlignedMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%7.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%9.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%10.2f", d);
    else
        printf("%11.3f", d);
}

원하는 필드 너비를 통과하는 함수로 변환할 수도 있습니다.

void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%*.0f", w-4, d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%*.1f", w-2, d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%*.2f", w-1, d);
    else
        printf("%*.3f", w, d);
}

범위의 첫 번째 문자를 문자열(오른쪽 끝)로 검색합니다.1로.9(ASCII 값)49-57)그럼null(로 설정)0) 각 문자 권리 - 아래 참조:

void stripTrailingZeros(void) { 
    //This finds the index of the rightmost ASCII char[1-9] in array
    //All elements to the left of this are nulled (=0)
    int i = 20;
    unsigned char char1 = 0; //initialised to ensure entry to condition below

    while ((char1 > 57) || (char1 < 49)) {
        i--;
        char1 = sprintfBuffer[i];
    }

    //null chars left of i
    for (int j = i; j < 20; j++) {
        sprintfBuffer[i] = 0;
    }
}

다음과 같은 경우(반올림 오류 및 음수 값의 문제가 있을 수 있습니다. 디버깅은 독자에게 연습으로 남겨집니다).

printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));

약간 프로그램적이지만 최소한 문자열 조작은 하지 않습니다.

다음은 저의 첫 번째 답변입니다.

무효xprintfloat(char *형식, float f){문자 s[50];
*charp;
sprintf(s, format, f);for(p=s; *p; ++p)이 경우. == *p) {한편 ++p);반면, sp0'==*--p) *p = '\0';}printf(rintf)%s", s);}

기존의 버그:형식에 따라 버퍼 오버플로가 발생할 수 있습니다." " 가 %f 이외의 이유로 존재할 경우 잘못된 결과가 발생할 수 있습니다.

상기의 약간의 변화:

  1. 케이스(100.0)의 기간을 생략합니다.
  2. 1교시 처리 후 휴식.

코드:

void EliminateTrailingFloatZeros(char *iValue)
{
  char *p = 0;
  for(p=iValue; *p; ++p) {
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
      if(*p == '.') *p = '\0';
      break;
    }
  }
}

아직 오버플로우 가능성이 있으니 주의하세요;P

난 네가 이 모든 것들을printf("%.8g",value);

사용하시는 경우"%.6g"32.230210과 같은 수치에서는 원하는 출력을 얻을 수 없습니다.32.23021하지만 인쇄된다.32.2302

같은 문제에 부딪혀, 2배 정밀도는 소수점 15, 플로트 정밀도는 소수점 6으로 되어 있기 때문에, 2개의 함수에 각각 기입했습니다.

#include <stdio.h>
#include <math.h>
#include <string>
#include <string.h>

std::string doublecompactstring(double d)
{
    char buf[128] = {0};
    if (isnan(d))
        return "NAN";
    sprintf(buf, "%.15f", d);
    // try to remove the trailing zeros
    size_t ccLen = strlen(buf);
    for(int i=(int)(ccLen -1);i>=0;i--)
    {
        if (buf[i] == '0')
            buf[i] = '\0';
        else
            break;
    }

    return buf;
}

std::string floatcompactstring(float d)
{
    char buf[128] = {0};
    if (isnan(d))
        return "NAN";
    sprintf(buf, "%.6f", d);
    // try to remove the trailing zeros
    size_t ccLen = strlen(buf);
    for(int i=(int)(ccLen -1);i>=0;i--)
    {
        if (buf[i] == '0')
            buf[i] = '\0';
        else
            break;
    }

    return buf;
}

int main(int argc, const char* argv[])
{
    double a = 0.000000000000001;
    float  b = 0.000001f;

    printf("a: %s\n", doublecompactstring(a).c_str());
    printf("b: %s\n", floatcompactstring(b).c_str());
    return 0;
}

출력은

a: 0.000000000000001
b: 0.000001

난 그게 필요했고 팍스디아블로의 첫 번째 답변이 효과가 있었어.하지만 저는 잘라낼 필요가 없었고 아래 버전이 조금 더 빠를 수도 있습니다."." 뒤에 문자열 끝(EOS) 검색을 시작합니다. EOS의 위치는 1개뿐입니다.

//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf
//adapted from paxdiablo (removed truncating)
char StringForDouble[50];
char *PointerInString;
void PrintDouble (double number) {
  sprintf(StringForDouble,"%.10f",number); // convert number to string
  PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any
  if(PointerInString!=NULL) {
    PointerInString=strchr(&PointerInString[0],'\0'); // find end of string
    do{
      PointerInString--;
    } while(PointerInString[0]=='0'); // remove trailing zeros
    if (PointerInString[0]=='.') { // if all decimals were zeros, remove "."
      PointerInString[0]='\0';
    } else {
      PointerInString[1]='\0'; //otherwise put EOS after the first non zero char
    }
  }
  printf("%s",&StringForDouble[0]);
}

언급URL : https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf

반응형