C examples for Language Basics:Variable
The floating-point types can store real numbers with different levels of precision.
#include <stdio.h> int main() {//from w w w. ja v a2s . c o m float myFloat; /* ~7 digits */ double myDouble; /* ~15 digits */ long double myLD; /* typically same as double */ }
A float can accurately represent about 7 digits.
A double can handle around 15 of them.
#include <stdio.h> int main() {/* w w w.j a v a 2 s . co m*/ float myFloat = 12345.678; printf("%f", myFloat); /* "12345.677734" */ }
You can limit the decimal places to two in the following way.
#include <stdio.h> int main() {/*from w w w. j av a2 s .co m*/ float myFloat = 12345.678; printf("%.2f", myFloat); /* "12345.68" */ }
Floating-point numbers can be expressed using decimal, exponential, or hexadecimal notation.
Exponential scientific notation is used by adding E or e followed by the decimal exponent.
The hexadecimal floating-point notation uses P or p to specify the binary exponent.
#include <stdio.h> int main() {/* ww w.j a v a 2s . com*/ float myFloat = 12345.678; double fDec = 1.23; double fExp = 3e2; /* 3*10^2 = 300 */ double fHex = 0xAA2; /* 10*2^2 = 40 */ }