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

Type casting

We can achieve a similar result though, using what's called a cast. This is a command in which we ask Java to treat a variable of one type like it is another one. Here we're circumventing Java's natural inclination to treat iNumber1 and iNumber2 as integers. We're stepping in and saying, "You know what Java, treat this number here as a float," and we're assuming some responsibility when we do this. Java will attempt to do what we ask, but if we choose poorly and attempt to cast one object to an object that it cannot, our program will crash.

Fortunately, we're working with primitives here, and primitive types know how to act like another type. So, we can cast the variable iNumber1 to temporarily operate like a floating-point number by prefacing it with (float):

float fNumber = (float)iNumber1/iNumber2; 

Now if we run our program, we'll see the expected result of 5/6:

That's a pretty solid introduction to working with floating-point numbers, which we're going to use just about any time we want to work with numbers in their mathematical sense rather than as integers for counting whole objects.

主站蜘蛛池模板: 礼泉县| 鲁甸县| 汕头市| 克拉玛依市| 许昌市| 东明县| 台湾省| 子洲县| 汝阳县| 陆川县| 焉耆| 皋兰县| 渭南市| 霍林郭勒市| 尼勒克县| 郯城县| 澜沧| 靖安县| 新密市| 来凤县| 广河县| 阜宁县| 兰考县| 忻城县| 永靖县| 黑山县| 平邑县| 资源县| 四川省| 剑河县| 玛纳斯县| 马公市| 虹口区| 大同市| 望城县| 徐州市| 抚远县| 沙河市| 阿勒泰市| 南川市| 双桥区|