Now I solve the problem, it seems that everything has been implemented correctly, but the test fails.

The essence of the task is as follows:

Round all elements of the matrix to an integer.

Use rounding to the nearest integer - the number is rounded to a whole, the difference modulus with which this number is minimal:

if N + 1 sign <5, then the N-th sign is retained, and N + 1 and all subsequent ones are zeroed if N + 1 sign ≥ 5, then the N-th sign is increased by one, and N + 1 and all subsequent ones are zeroed.

Here is my code

public static void task22 () { Scanner scan = new Scanner (System.in); int n = Integer.parseInt (scan.nextLine ()); double[][] matrix = new double[n][n]; System.out.println (n); System.out.println("\t"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = Double.parseDouble (scan.next ()); System.out.print (Math.round (matrix[i][j]) + "\t"); } System.out.println ("\n\t"); } } 

Question: how to make -1.5 rounded to 2 and not to 1?

Test

  • Round modulo, and then return the sign - user31238
  • How to make -1.5 rounded to 2 and not to 1? maybe up to -2? - Senior Pomidor

3 answers 3

Try this:

 Math.signum(number) * Math.round(Math.abs(number)) 

    For numbers less than zero - change the sign, round, change the sign again ...

        Scanner scan = new Scanner (System.in); int n = Integer.parseInt (scan.nextLine ()); double[][] matrix = new double[n][n]; System.out.println (n); System.out.println("\t"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = Double.parseDouble (scan.next ()); BigDecimal bigDecimal = new BigDecimal(matrix[i][j]).setScale(0, RoundingMode.HALF_UP); System.out.print (bigDecimal.toString() + "\t"); } System.out.println ("\n\t"); } }