74 lines
1.8 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// operators/MathOps.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-06-15 17:47:35 -07:00
// Demonstrates the mathematical operators.
import java.util.*;
public class MathOps {
public static void main(String[] args) {
// Create a seeded random number generator:
Random rand = new Random(47);
int i, j, k;
// Choose value from 1 to 100:
j = rand.nextInt(100) + 1;
2015-11-03 12:00:44 -08:00
System.out.println("j : " + j);
2015-06-15 17:47:35 -07:00
k = rand.nextInt(100) + 1;
2015-11-03 12:00:44 -08:00
System.out.println("k : " + k);
2015-06-15 17:47:35 -07:00
i = j + k;
2015-11-03 12:00:44 -08:00
System.out.println("j + k : " + i);
2015-06-15 17:47:35 -07:00
i = j - k;
2015-11-03 12:00:44 -08:00
System.out.println("j - k : " + i);
2015-06-15 17:47:35 -07:00
i = k / j;
2015-11-03 12:00:44 -08:00
System.out.println("k / j : " + i);
2015-06-15 17:47:35 -07:00
i = k * j;
2015-11-03 12:00:44 -08:00
System.out.println("k * j : " + i);
2015-06-15 17:47:35 -07:00
i = k % j;
2015-11-03 12:00:44 -08:00
System.out.println("k % j : " + i);
2015-06-15 17:47:35 -07:00
j %= k;
2015-11-03 12:00:44 -08:00
System.out.println("j %= k : " + j);
2015-06-15 17:47:35 -07:00
// Floating-point number tests:
float u, v, w; // Applies to doubles, too
v = rand.nextFloat();
2015-11-03 12:00:44 -08:00
System.out.println("v : " + v);
2015-06-15 17:47:35 -07:00
w = rand.nextFloat();
2015-11-03 12:00:44 -08:00
System.out.println("w : " + w);
2015-06-15 17:47:35 -07:00
u = v + w;
2015-11-03 12:00:44 -08:00
System.out.println("v + w : " + u);
2015-06-15 17:47:35 -07:00
u = v - w;
2015-11-03 12:00:44 -08:00
System.out.println("v - w : " + u);
2015-06-15 17:47:35 -07:00
u = v * w;
2015-11-03 12:00:44 -08:00
System.out.println("v * w : " + u);
2015-06-15 17:47:35 -07:00
u = v / w;
2015-11-03 12:00:44 -08:00
System.out.println("v / w : " + u);
2015-06-15 17:47:35 -07:00
// The following also works for char,
// byte, short, int, long, and double:
u += v;
2015-11-03 12:00:44 -08:00
System.out.println("u += v : " + u);
2015-06-15 17:47:35 -07:00
u -= v;
2015-11-03 12:00:44 -08:00
System.out.println("u -= v : " + u);
2015-06-15 17:47:35 -07:00
u *= v;
2015-11-03 12:00:44 -08:00
System.out.println("u *= v : " + u);
2015-06-15 17:47:35 -07:00
u /= v;
2015-11-03 12:00:44 -08:00
System.out.println("u /= v : " + u);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
j : 59
k : 56
j + k : 115
j - k : 3
k / j : 0
k * j : 3304
k % j : 56
j %= k : 3
v : 0.5309454
w : 0.0534122
v + w : 0.5843576
v - w : 0.47753322
v * w : 0.028358962
v / w : 9.940527
u += v : 10.471473
u -= v : 9.940527
u *= v : 5.2778773
u /= v : 9.940527
2015-09-07 11:44:36 -06:00
*/