C/printf: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
m →‎pierwszy: konwersja
m →‎Konwersja: 2 liczba
Linia 183:
------->
====Konwersja ====
Konwersja 1 liczby typu double na łańcuch :
 
<source lang=c>
/*
Linia 198:
size_t size = sizeof(double);
double d = 234.567;
char s[size]; // 16
snprintf(s, size, "%f", d); // convert double to string
Linia 206 ⟶ 205:
return 0;
}
</source>
 
 
 
Konwersja 2 liczb typu double na łańcuch :
<source lang =c>
/*
 
http://stackoverflow.com/questions/7228438/convert-double-float-to-string
 
 
 
http://linux.die.net/man/3/snprintf
The conversion specifier : f, F
The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd,
where the number of digits after the decimal-point character is equal to the precision specification.
If the precision is missing, it is taken as 6;
 
 
The precision
the number of digits to appear after the radix character for a, A, e, E, f, and F conversions,
*/
#include <stdio.h>
 
 
 
 
 
 
 
int main() {
 
/* And remember to allow space for :
- the trailing null '\0' character!
- comma
*/
 
int n= 2; // number of doubles
size_t z_size = n*sizeof(double) +4;
// doubles with 15 decimal digits after comma
double d1 = -1.123456789012345;
double d2 = -2.123456789012345;
char sz[z_size]; //
// The return value is the number of characters which would be generated for the given input, excluding the trailing null, as per ISO C99. If the return is greater than or equal to size, the resulting string is truncated.
int rz; // return value , Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
 
// double has 15–17 significant decimal digits precision.
rz = snprintf(sz, z_size, "%f,%f", d1, d2); // convert 2 double to string with rounding on 6 decimal place
 
printf("d = %s\n", sz); // check
printf ("good size of string is r = %d but now true size is = %zd \n", rz, z_size);
 
return 0;
}
</source>