06.09.2021 Views

Java with BlueJ, 2016a

Java with BlueJ, 2016a

Java with BlueJ, 2016a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

26 CHAPTER 2. BASICS<br />

2.3.2 Numeric Data Types: float, double<br />

These data types are used to represent values that have decimal places. For<br />

example, the numbers 11.5, 12.25, -300.123, and0.0 are written <strong>with</strong><br />

decimal places. Even the value zero written as 0.0 is a double.<br />

The float and double types differ <strong>with</strong> respect to the number of significant<br />

digits they store (approximately 7 for float and 16 for double) and the overall<br />

magnitude of a value that can be represented. The table below shows the<br />

amount of memory used and the maximum value per type:<br />

data type memory maximum<br />

float 4bytes 3.4028235 × 10 38<br />

double 8bytes 1.7976931348623157 × 10 308<br />

Of course a programmer can perform calculations on doubles andfloats.<br />

The operators we will discuss at this time include +, -, *, and / as shown<br />

in the following table.<br />

operator example of use example’s result<br />

+ 7.1 + 1.1 8.2<br />

- 12.1 - 5.0 7.1<br />

* 2.2 * 2.2 4.84<br />

/ 10 / 4 2.5<br />

Listing 2.4 illustrates some simple double calculations in order to compute<br />

and display fuel consumption as litres per 100 kilometres travelled.<br />

Listing 2.4: Perform simple double calculations<br />

1 public class FuelConsumption<br />

2 {<br />

3 public static void main(String[] args)<br />

4 {<br />

5 // Calculate fuel consumption as<br />

6 // litres per 100 kilometres travelled.<br />

7 // All calculations involve doubles.<br />

8 double litres , km, km100;<br />

9 litres = 60.6;<br />

10 km = 500.25;<br />

11 km100 = km/100.0;<br />

12 // calculate litres per 100km<br />

13 double consumption = litres/km100;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!