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

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:

主站蜘蛛池模板: 马鞍山市| 郸城县| 长子县| 广昌县| 株洲县| 开平市| 鱼台县| 鄂托克前旗| 云梦县| 余干县| 翁牛特旗| 岳普湖县| 六盘水市| 涟水县| 合水县| 个旧市| 克山县| 鞍山市| 拉萨市| 新巴尔虎右旗| 大姚县| 内乡县| 金秀| 四会市| 黄平县| 苗栗县| 晋州市| 高尔夫| 和平区| 东港市| 左云县| 方城县| 昌黎县| 汨罗市| 青川县| 临夏市| 綦江县| 阳朔县| 峨眉山市| 陇南市| 隆回县|