Computer Arithmetic

advertisement
//
//
//
//
Author: JChildress
Description: Examples of arithmetic
/*
Pie = 3.141592653589793
z = 13.5
b = 159.5
i = 15
j = 68
k = 0
-27.6
*/
public class Arith
{
public static void main( String[] args )
{
final double Pie = Math.PI;
double x = 14.5;
double y = 11.0;
double b , z;
int n = 9;
int m = 5;
int i, j, k;
System.out.printf( "Pie = " + Pie + "\n" );
// Pie = 3.141592653589793
z = x - n/m;
System.out.printf( "z = " + z + "\n" );
// z = 13.5
b = x * y + m / n * 2 ;
System.out.printf( "b = " + b + "\n" );
// b = 159.5
i = (int)( x + .5 );
System.out.printf( "i = " + i + "\n" );
// i = 15
j = (int)( x * m - n % m );
System.out.printf( "j = " + j + "\n" );
// j = 68
k = (int)( 1. / -m );
System.out.printf( "k = " + k + "\n" );
// k = 0
b = 10.0;
double p = 4.8, q = -2.0, r = 8.5, s = 12.0, t = .5;
z = (p/-q + (r - s + t) * b); //-27.6
System.out.printf( "z = " + z + "\n" ); //-27.6
}
}
Java Computer Arithmetic
The algebraic rules of precedence are used for Java arithmetic. However there are some
special rules that apply to integer type data and the mixing of integer and floating point
data. Here is the list of rules for Java computer arithmetic.
1. The Java assignment operator is the equal symbol, =. The assignment operator
assigns values from right to left only: x = 5 implies the memory cell assigned to x
contains the value 5.
2. Arithmetic operators have two operands.
a. Arithmetic operands will be either
i. Two’s complement integer. The Java keywords for integer
variables are byte, short, int, or long. Integer numbers only have
digits to the left of the decimal point.
ii. IEEE floating point. The Java keywords for floating point are float
and double. Floating point numbers can have digits to the left and
right of the decimal.
3. A decimal point distinguishes if a literal number is either integer or floating point.
4. The Java arithmetic operators are: +, -, *, /, %
a. + addition,
int x = 3 + 7;
b. – subtraction,
double y = 17.0 – 5.;
c. * multiplication,
int z = x * 9;
d. / division,
double u = 6 / 4;
i. Integer division truncates (drops) all digits to the right of the
decimal without rounding.
ii. Floating point division can produce a result with digits to the right
of the decimal.
e. % modulo,
int t = 17 % 3; // In this case,
t = 2
Modulo computes the remainder from division.
5. Mixing of integer and floating point operands is allowed. However, the integer
operand will be promoted to a floating point operand. The result is always floating
point.
6. An operand can be cast to a different data type: int a = (int) 3.14; In
this case, the variable a contains the integer value 3. Casting is required when a
floating point operand is assigned to an integer operand.
Download