官术网_书友最值得收藏!

Floating point variables

When we're simply counting and manipulating whole objects, integers are fantastic. However, sometimes we need to deal with numbers in a more mathematical sense, and we need a data type that will allow us to express ideas that are not entirely whole numbers. Floating-point numbers, or floats, are a Java primitive type that allow us to express numbers that have decimal points and fractions. In this section, we'll modify some float and integer variables side by side to see how they are similar and different.

Let's create a new Java project (you know the drill by now) and call it FloatingPointNumbers. Let's start by declaring two variables: one integer (iNumber) and one float (fNumber). As we know, once we've declared these variables, we're free to modify and assign values to them in our Java program later. This time, let me show you that we can also modify and assign to these variables in the same line that they're declared. So where I have declared my iNumber integer variable, I'm free to immediately give it the value of 5:

package floatingpointnumbers; 
 
public class FloatingPointNumbers { 
     
    public static void main(String[] args) { 
        int iNumber = 5; 
        float fNumber; 
    } 
} 

Notice that if we try and do something very similar with our float variable, NetBeans will yell at us, by displaying a light bulb and red dot on the left-hand side:

In fact, if we attempt to compile our program, we'll get a legitimate compiler error message:

Let's analyze why this happens. When we use an explicit number in Java, that is, typing out the digits rather than working with a variable, that explicit number is still given a type by Java. So when we type out a number without any decimal places, the type that the number is assumed to be is an integer. So our assignment works just great. However, a number with decimal places is assumed to be of this type and is called double; it's a sister type of the float data type, but it's not quite the same. We'll talk about double a little later. Right now, what we need to do is tell Java to treat 5.5 as a float type number instead of double. To do this, all we need to do is put f after the digits, as follows:

float fNumber = 5.5f; 

You'll see that the bulb and red dot have disappeared. To make sure we get the syntax right, let's give our program some super basic functionality. Let's use System.out.println() to print our integer number and then our floating-point number variable in sequence:

System.out.println(iNumber); 
System.out.println(fNumber); 

When we build this program, our compiler error goes away, and when we run it, we see the two assigned values as expected. Nothing too exciting there:

主站蜘蛛池模板: 梁平县| 樟树市| 巍山| 宜川县| 周宁县| 大理市| 介休市| 衡阳市| 长沙市| 韩城市| 杭锦后旗| 谷城县| 思茅市| 盐津县| 拜城县| 三江| 论坛| 湖州市| 沁阳市| 上栗县| 阳泉市| 温泉县| 彩票| 公安县| 曲阜市| 成都市| 长顺县| 新乡县| 东乌珠穆沁旗| 习水县| 岳阳县| 土默特左旗| 顺平县| 舟曲县| 阳西县| 门源| 雷波县| 姜堰市| 临沂市| 都兰县| 洮南市|