LUNDS TEKNISKA HÖGSKOLA Institutionen för datavetenskap EDAA20 Programmering och databaser HT 2016 Lösningsförslag till övning 3, EDAA20 Programmering och databaser 1. a) y = Math.sin(Math.toRadians(20)); eller y = Math.sin(20 * Math.PI / 180); b) z = a * Math.exp(x) + b * Math.exp(-Math.cos(x)); c) hyp = Math.hypot(a, b); 2. 3. // eller: hyp = Math.sqrt(a * a + b * b); (int) Math.round(x) a) if (n % 2 == 0) ... b) if (n % 10 == 0) ... c) digit1 = number / 100; digit2 = (number % 100) / 10; digit3 = number % 10; 4. // eller: digit2 = (number / 10) % 10; a) a > 5 b) a > 2 c) a <= 2 d) a <= 2 || a >= 9 e) a >= 0 && a <= 10 f) ready g) !ready 5. public class TwoRandomNumbers { public static void main(String[] args) { Random rand = new Random(); int nbr1 = rand.nextInt(100) + 1; int nbr2 = rand.nextInt(100) + 1; while (nbr2 == nbr1) { nbr2 = rand.nextInt(100) + 1; } System.out.print("Två slumptal: "); if (nbr1 < nbr2) { System.out.println(nbr1 + ", " + nbr2); } else { System.out.println(nbr2 + ", " + nbr1); } } } 6. Scanner scan = new Scanner(System.in); double limit = scan.nextDouble(); double smallSum = 0; double largeSum = 0; for (int i = 0; i < 100; i++) { double nbr = scan.nextDouble(); if (nbr < limit) { smallSum = smallSum + nbr; } else if (nbr > limit) { largeSum = largeSum + nbr; } 1 2 } scan.close(); System.out.println("Summan av tal < " + limit + " = " + smallSum); System.out.println("Summan av tal > " + limit + " = " + largeSum); Observera att man måste skriva ...else if (nbr > limit) ... och inte bara ...else .... I annat fall kommer tal lika med limit med i largeSum. 7. public class HugeSalary { public static void main (String[] args) { int daySalary = 1; int totalSalary = 0; int days = 0; while (totalSalary < 1000000) { totalSalary = totalSalary + daySalary; days = days + 1; daySalary = 2 * daySalary; } System.out.println("Man måste arbeta " + days + " dagar."); } } 8. public class TemperatureStatistics { public static void main (String[] args) { final int NBR = 30; double sum = 0; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; Scanner scan = new Scanner(System.in); for (int i = 0; i < NBR; i++) { double temp = scan.nextDouble(); sum = sum + temp; if (temp < min) { min = temp; } if (temp > max) { max = temp; } } scan.close(); double average = sum / NBR; System.out.println("Lägsta temperatur: " + min + " grader"); System.out.println("Högsta temperatur: " + max + " grader"); System.out.println("Medeltemperatur: " + average + " grader"); } }