Do Some Math Solution

So now you have a new tool in your tool box - the mysterious 'printf' in which the 'f' stands for 'flags or formatting'. It's incredibly useful for problems that specify you must print to a certain number of decimal places, or offset the text a certain number of spaces. And to be honest, it's sometimes just easier to type the entire String out and then place the variables at the ends - rather than do some funky concatenation.

Integer division is a common issue on this problem. This is when you divide two numbers with the datatype int and it truncates towards zero. For example, 3 / 5 = 0 and 6 / 4 = 1. To get around the problem of integer division, take in the numbers with the datatype double.

import java.util.*;
import java.io.*;
import static java.lang.System.*;

public class Main {
    public static void main(String[]args) throws IOException {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt(); //take in T specifying T cases or data sets
        for (int i = 0; i < T; i++) { //loop through T times
            double a = sc.nextDouble(); //each dataset has two numbers
            double b = sc.nextDouble(); // taking in a & b in as doubles makes it easier to do math with
            // since the output expects you to print to the first decimal place -
            // meaning it wants you to avoid integer division.

            // printf is useful for formatting, especially in cases where the judges
            // want you to print to a specified number of decimal places
            out.printf("%.1f + %.1f = %.1f\n", a, b, a + b);
            out.printf("%.1f - %.1f = %.1f\n", a, b, a - b);
            out.printf("%.1f * %.1f = %.1f\n", a, b, a * b);
            out.printf("%.1f / %.1f = %.1f\n\n", a, b, a / b);
        }
    }
}

The next problem is a certainly challenging, so best of luck space cadet!

results matching ""

    No results matching ""