- Java Programming for Beginners
- Mark Lassoff
- 191字
- 2021-07-02 15:22:45
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.
- VMware View Security Essentials
- Cocos2D-X權(quán)威指南(第2版)
- JavaScript:Functional Programming for JavaScript Developers
- Practical Windows Forensics
- UML+OOPC嵌入式C語(yǔ)言開(kāi)發(fā)精講
- Blender 3D Incredible Machines
- 老“碼”識(shí)途
- 深入理解Elasticsearch(原書(shū)第3版)
- 零基礎(chǔ)Java學(xué)習(xí)筆記
- Java實(shí)戰(zhàn)(第2版)
- TMS320LF240x芯片原理、設(shè)計(jì)及應(yīng)用
- Visual Basic 6.0程序設(shè)計(jì)實(shí)驗(yàn)教程
- 從零開(kāi)始學(xué)Android開(kāi)發(fā)
- Python函數(shù)式編程(第2版)
- Instant jQuery Boilerplate for Plugins