Homework 1.5: casting and range of Variables


Table of Contents

Practice Problems

FRQ Problems


//Q1
int a = 5, b = 2;
System.out.println(a / b);
System.out.println((double)a / b);
System.out.println((int)3.9);
System.out.println((int)(3.9 + 0.5));

2
2
2.0
2.5
//Q2
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
int x = Integer.MAX_VALUE;
int y = x + 2;
System.out.println(x);
System.out.println(y);
2147483647
-2147483647

FRQ 1: Average with correct casting Problem: Write a method avgInt that takes two int values and returns their average as a double, preserving the .5 if present.

public static double avgInt(int a, int b) {
    return ((double)a + b) / 2.0;
}

FRQ 2: Percentage Problem: Given int correct and int total, compute the percentage as a double from 0.0 to 100.0 without losing fractional precision.

public static double percent(int correct, int total) {
    if (total == 0) return 0.0;
    return 100.0 * ((double) correct) / total;
}

FRQ 3: Safe remainder Problem: Implement safeMod(int a, int b) that returns a % b, but if b == 0, it should return 0 instead of throwing.

public static int safeMod(int a, int b) {
    if (b == 0) return 0;
    return a % b;
}