Casting HW
For the thinkers group. 1.5.
Practice: predict the output (Java)
Q1:
2
2
2.0
2.5
Q2:
-2
-3
3
Q3:
2147483647
-2147483647
FRQs
public class FRQ {
// FRQ 1. Average with correct casting
public static double avgInt(int a, int b) {
return (a + b) / 2.0;
}
// FRQ 2. Percentage
public static double percent(int correct, int total) {
if (total == 0) {
return 0.0; // avoid division by zero
}
return (100.0 * correct) / total;
}
// FRQ 3. Safe remainder
public static int safeMod(int a, int b) {
if (b == 0) {
return 0;
}
return a % b;
}
public static void main(String[] args) {
// Test FRQ 1
System.out.println("FRQ1 avgInt(3, 56) = " + avgInt(3, 56)); // should preserve .5 if any
// Test FRQ 2
System.out.println("FRQ2 percent(45, 60) = " + percent(45, 60)); // expect 75.0
// Test FRQ 3
System.out.println("FRQ3 safeMod(10, 3) = " + safeMod(10, 3)); // expect 1
System.out.println("FRQ3 safeMod(10, 0) = " + safeMod(10, 0)); // expect 0 (safe case)
}
}
System.out.println(FRQ.avgInt(3,5));
System.out.println(FRQ.percent(2,7));
System.out.println(FRQ.safeMod(29,58));
4.0
28.571428571428573
29