4.9 Floating-Point Divide Versus Integer Divide
The division operator is special. There is a vast difference between an integer divide and a floating-point divide. In an integer divide, the result is truncated (any fractional part is discarded). For example, the integer divide value of 19/10 is 1.
If either the divisor or the dividend is a floating-point number, a floating-point divide is executed. In this case 19.0/10.0 is 1.9. (19/10.0 and 19.0/10 are also floating-point divides; however, 19.0/10.0 is preferred for clarity.) There are several examples in Table 4-2.
Table 4-2. Expression examples
|
19 / 10
|
1
|
Integer
|
19.0 / 10.0
|
1.9
|
Floating point
|
19.0 / 10
|
1.9
|
Floating point (for clarity, do not code like this)
|
19 / 10.0
|
1.9
|
Floating point (for clarity, do not code like this)
|
C++ allows the assignment of an integer expression to a floating-point variable. It will automatically perform the integer-to-floating-point conversion and then make the assignment. A similar conversion is performed when assigning a floating-point number to an integer variable. Floating-point numbers are truncated when assigned to integer variables.
Example 4-3 demonstrates a variety of floating-point and integer operations.
Example 4-3. float1/float1.cpp
int integer; // an integer float floating; // a floating-point number
int main( ) { floating = 1.0 / 2.0; // assign "floating" 0.5
integer = 1 / 3; // assign integer 0
floating = (1 / 2) + (1 / 2); // assign floating 0.0
floating = 3.0 / 2.0; // assign floating 1.5
integer = floating; // assign integer 1
return (0); }
Notice that the expression 1/2 is an integer expression resulting in an integer divide and an integer result of 0.
Question 4-2: Why does Example 4-4 print "The value of 1/3 is 0"? What must be done to this program to fix it?
Example 4-4. float2/float2.cpp
#include <iostream>
float answer; // the result of the divide
int main( ) { answer = 1/3; std::cout << "The value of 1/3 is " << answer << "\n"; return (0); }
|
No comments:
Post a Comment