printf ()에서 후행 0을 피하십시오.
나는 printf () 함수 군에 대한 형식 지정자를 계속해서 고민하고있다. 내가 원하는 것은 소수점 뒤에 최대 주어진 자릿수로 이중 (또는 부동)을 인쇄 할 수있는 것입니다. 내가 사용하는 경우 :
printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
나는 얻다
359.013
359.010
원하는 대신
359.013
359.01
아무도 나를 도울 수 있습니까?
이는 일반 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
소수를 제외한 모든 것을 제거한 다음 후행 0 (및 모두 0 인 경우 소수점)을 제거합니다.
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.12399
로 0.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);
(또는 morphNumericString
끝에서 호출 nDecimals
하지만이 경우 두 가지를 하나의 함수로 결합 할 것입니다) 그러면 다음과 같이 끝납니다.
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
후행 0을 제거하려면 "% g"형식을 사용해야합니다.
float num = 1.33;
printf("%g", num); //output: 1.33
질문이 약간 명확해진 후 0을 억제하는 것이 요청 된 유일한 것이 아니라 출력을 소수점 세 자리로 제한해야한다는 것입니다. sprintf 형식 문자열만으로는 불가능하다고 생각합니다. 으로 인원 디아블로는 지적, 문자열 조작이 요구 될 것이다.
나는 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이 제거됩니다.
- 그것은 수학적으로 옳습니다 (맞습니까?)
- 첫 번째 소수점이 0 일 때도 작동합니다.
불행히도이 대답은 sprintf
문자열을 반환하지 않으므로 두 줄입니다.
내가 범위의 첫 번째 문자의 문자열 (시작 오른쪽)를 검색 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));
약간 프로그래밍 방식이지만 적어도 문자열 조작을 수행하지는 않습니다.
간단한 솔루션이지만 작업을 완료하고 알려진 길이와 정밀도를 할당하며 지수 형식이 될 가능성을 방지합니다 (% 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);
}
소수점 이하 두 자리를 원하면 "elses"를 추가하거나 제거하십시오. 소수점 4 자리; 기타
예를 들어 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);
}
게시 된 솔루션 중 일부에서 문제를 발견했습니다. 위의 답변을 바탕으로 이것을 정리했습니다. 그것은 나를 위해 일하는 것 같습니다.
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);
}
Some of the highly voted solutions suggest the %g
conversion specifier of printf
. This is wrong because there are cases where %g
will produce scientific notation. Other solutions use math to print the desired number of decimal digits.
I think the easiest solution is to use sprintf
with the %f
conversion specifier and to manually remove trailing zeros and possibly a decimal point from the result. Here's a C99 solution:
#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;
}
Note that the characters used for digits and the decimal separator depend on the current locale. The code above assumes a C or US English locale.
Here is my first try at an answer:
void xprintfloat(char *format, float f) { char s[50]; char *p; sprintf(s, format, f); for(p=s; *p; ++p) if('.' == *p) { while(*++p); while('0'==*--p) *p = '\0'; } printf("%s", s); }
Known bugs: Possible buffer overflow depending on format. If "." is present for other reason than %f wrong result might happen.
Why not just do this?
double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);
Slight variation on above:
- Eliminates period for case (10000.0).
- Breaks after first period is processed.
Code here:
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;
}
}
}
It still has potential for overflow, so be careful ;P
Your code rounds to three decimal places due to the ".3" before the f
printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
Thus if you the second line rounded to two decimal places, you should change it to this:
printf("%1.3f", 359.01335);
printf("%1.2f", 359.00999);
That code will output your desired results:
359.013
359.01
*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:
printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);
The Following program source code was my test for this answer
#include <cstdio>
int main()
{
printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);
while (true){}
return 0;
}
참고URL : https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf
'program story' 카테고리의 다른 글
task.Result?와 동일한 완료된 작업을 기다립니다. (0) | 2020.08.15 |
---|---|
객체 인 것처럼 명명 된 속성을 배열에 추가 할 수있는 이유는 무엇입니까? (0) | 2020.08.15 |
nServiceBus vs Mass Transit vs Rhino Service Bus vs 기타? (0) | 2020.08.15 |
MS SQL Server 2008 용 포트를 찾는 방법은 무엇입니까? (0) | 2020.08.14 |
Spring-현재 스레드에 사용할 수있는 실제 트랜잭션이있는 EntityManager가 없습니다. '지속성'호출을 안정적으로 처리 할 수 없습니다. (0) | 2020.08.14 |