Casting and Range of Variables Homework

Practice: predict the output (Java)

Q1
Prediction Output
  • 2
  • 2
  • 2.0
  • 2.5
Answer
int a = 10, b = 4;
System.out.println(a / b);
System.out.println(a % b);
System.out.println((double)(a / b));
System.out.println((double)a / b);

2
2
2.0
2.5
Q2
Prediction Output
  • -2
  • -3
  • 3
Answer
double d = -2.6;
System.out.println((int)d);
System.out.println((int)(d - 0.5));
System.out.println((int)(-d + 0.5));

-2
-3
3
Q3
Prediction Output
  • 2147483647
  • -2147483647
Answer
int x = Integer.MAX_VALUE;
int y = x + 2;
System.out.println(x);
System.out.println(y);

2147483647
-2147483647

FRQ Homework

FRQ 1. Average with correct casting

public class FRQ1 {
    
    // Method to compute the average of two integers as a double
    public static double avgInt(int a, int b) {
        return ((double)a + b) / 2.0; // cast to double to preserve .5
    }

    public static void main(String[] args) {
        // Test examples
        System.out.println("Average of 3 and 4: " + avgInt(3, 4));   // 3.5
        System.out.println("Average of 10 and 2: " + avgInt(10, 2)); // 6.0
        System.out.println("Average of 5 and 6: " + avgInt(5, 6));   // 5.5
    }
}

// Run the main method
FRQ1.main(null);



Average of 3 and 4: 3.5
Average of 10 and 2: 6.0
Average of 5 and 6: 5.5

FRQ 2: Percentage Calculation

public class FRQ2 {

    // Method to compute percentage as a double
    public static double percent(int correct, int total) {
        if (total == 0) return 0.0;              // avoid division by zero
        return 100.0 * ((double) correct) / total; // cast to double for precision
    }

    public static void main(String[] args) {
        // Test examples
        System.out.println("Percentage 45/50: " + percent(45, 50));  // 90.0
        System.out.println("Percentage 7/12: " + percent(7, 12));    // 58.3333...
        System.out.println("Percentage 0/0: " + percent(0, 0));      // 0.0
    }
}

// Run the main method
FRQ2.main(null);



Percentage 45/50: 90.0
Percentage 7/12: 58.333333333333336
Percentage 0/0: 0.0

FRQ 3: Safe Remainder

public class FRQ3 {

    // Method to compute safe remainder
    public static int safeMod(int a, int b) {
        if (b == 0) return 0;   // avoid division by zero
        return a % b;
    }

    public static void main(String[] args) {
        // Test examples
        System.out.println("safeMod(10, 3): " + safeMod(10, 3));   // 1
        System.out.println("safeMod(7, -2): " + safeMod(7, -2));   // 1
        System.out.println("safeMod(-7, 2): " + safeMod(-7, 2));   // -1
        System.out.println("safeMod(5, 0): " + safeMod(5, 0));     // 0
    }
}

// Run the main method
FRQ3.main(null);



safeMod(10, 3): 1
safeMod(7, -2): 1
safeMod(-7, 2): -1
safeMod(5, 0): 0

MCQ Answers

Q1: C
Q2: D
Q3: B
Q4: B
Q5: B