C++ Crash Course: a fast-Paced Introduction



Yüklə 7 Mb.
Pdf görüntüsü
səhifə67/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   63   64   65   66   67   68   69   70   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

Floating-Point Literals
Floating-point literals are double precision by default. If you need single pre-
cision, use an 
f
or 
F
suffix; for extended precision, use 
l
or 
L
, as shown here:
float a = 0.1F;
double b = 0.2;
long double c = 0.3L;


36
Chapter 2
You can also use scientific notation in literals:
double plancks_constant = 6.62607004
u
e-34
v
;
No spaces are permitted between the significand (the base 
u
) and the 
suffix (the exponential portion 
v
).
Floating-Point Format Specifiers
The format specifier 
%f
displays a 
float
with decimal digits, whereas 
%e
displays the same number in scientific notation. You can let 
printf
decide 
which of these two to use with the 
%g
format specifier, which selects the 
more compact of 
%e
or 
%f
.
For 
double
, you simply prepend an 
l
(lowercase L) to the desired speci-
fier; for 
long double
, prepend an 
L
. For example, if you wanted a 
double
with 
decimal digits, you would specify 
%lf

%le
, or 
%lg
; for a long double, you 
would specify 
%Lf

%Le
, or 
%Lg
.
Consider Listing 2-3, which explores the different options for printing 
floating points.
#include
int main() {
double an = 6.0221409e23; 
u
printf("Avogadro's Number: %le
v
%lf
w
%lg
x
\n", an, an, an);
float hp = 9.75; 
y
printf("Hogwarts' Platform: %e %f %g\n", hp, hp, hp);
}
Avogadro's Number: 6.022141e+23
v
602214090000000006225920.000000
w
6.02214e+23
x
Hogwarts' Platform: 9.750000e+00 9.750000 9.75
Listing 2-3: A program printing several floating points
This program declares a 
double
called 
an
u
. The format specifier 
%le
v
gives you scientific notation 
6.022141e-23
, and 
%lf
w
gives the decimal rep-
resentation 
602214090000000006225920.000000
. The 
%lg
x
specifier chose the 
scientific notation 
6.02214e-23
. The 
float
called 
hp
y
produces similar 
printf
output using the 
%e
and 
%f
specifiers. But the format specifier 
%g
decided to 
provide the decimal representation 9.75 rather than scientific notation.
As a general rule, use 
%g
to print floating-point types.
N O T E
 
In practice, you can omit the 
l
 prefix on the format specifiers for 
double
, because 
printf
 promotes 
float
 arguments to 
double
 precision.

Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   63   64   65   66   67   68   69   70   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin