I am trying to print zeros to a certain length to compare with another numbers which is store as string, I was wondering how to do that?
Edit: added sample code
For example:
printf("%s\n", "References:\n3.141592653"
"58979323846264338327950288419716939937510582097494459230781640628620899");
printf("Monte Carlo: %d nodes over %d iterations calculated Pi as:\n%1.9f\n", numnodes,
final_iters,pi); //Print the calculated value of pi
The out is
References:
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899
Monte Carlo 16 nodes over 160000 iterations calculated Pi as:
3.142025000
How would I make the actual calculation fill in zeros to the end of the string?
转载于:https://stackoverflow.com/questions/53111724/printf-following-zeros-to-a-certain-degree
maybe this will help you. in comment the result, maybe there are better solution but this works. in printf
the %016 should be change to your max_buffer length or preferred range and don't forget to add 0 after %.
printf("%016f\n\n",3.142025000); //// 000000003.142025
///3.14159000000000000000000000000
#define MAX_BUFFER 32
float pi = 3.141592653;
char digit[MAX_BUFFER]={'\0'};
sprintf(digit, "%f", pi);
int l = strlen(digit);
int dif = MAX_BUFFER-l;
for(int i=0;i<dif;i++)
{
digit[i+l-1]='0';
}
printf("%s", digit);
How would I make the actual calculation fill in zeros to the end of the string?
Code could attempt various numeric approaches such as
printf("%1.9f%071d\n", pi, 0); // Print an extra int 0 with wide width padded with '0'
printf("%1.80f\n", pi); // Print with wide precision - (might not all be 0's)
Yet I worry that specifiers with large width/precision and number specifiers may break some printf()
implementation. so I'll add a text approach.
#define PI_STR "3.1415926535" \
"8979323846264338327950288419716939937510582097494459230781640628620899"
printf("%s\n", "References:\n" PI_STR);
// Remember length of reference pi string
int pi_ref_len = (sizeof PI_STR) - 1;
...
// Print computed pi & return count of characters printed
int pi_compute_len = printf("%1.9f", pi);
// Use a loop or print a portion of a string "0000...000"
char zeros[sizeof PI_STR];
memset(zeros, '0', sizeof zeros);
// v--- %s w/precision can print a non-null character terminated char array
printf("%.*s\n", pi_ref_len - pi_compute_len, zeros);