此刻只想哭,又收到 hackerRank 的 OA,真的太變態了 T_T
我這五天裡要準備一個 midterm, 一個作業,一個前端的 project, 一個變態的 hackerRankOA,這幾天好好努力吧!

# Set decimal places

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.

Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.

Example

There are elements, two positive, two negative and one zero. Their ratios are , and . Results are printed as:

0.400000
0.400000
0.200000

Function Description

Complete the plusMinus function in the editor below.

plusMinus has the following parameter(s):

  • int arr[n]: an array of integers

# Solution

# 不用 round up 的時候

主要是要知道怎麼設 decimal places

  1. String.format("%.6f", n)
  • 6f 是小數點後多少位
  • n 是數值

但問題是不能 round up 吧

public class LimitDecimalDemo {
  public static void main(String[] args) {
    
    Double n = 3.0;
    System.out.println(String.format("%.5f", n));
    System.out.println(String.format("%.3f", n));
    
  }
  1. System.out.format("%.3f", n)
    和上面的一樣但不會 print 出來

# 要 round up 的話

  1. DecimalFormat
    如果要 round up, 可以用 RoundingMode.CEILING
    這個太煩了,建議用下面
Double d = 1234.675389;
// 先定義要多少位,小數點後的 ## 就是代表多少位
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.println("Original input value: " + d);
    System.out.println("Using DecimalForamt: " + df.format(d));
    
    df.setRoundingMode(RoundingMode.DOWN);
    System.out.println("Using Rounding mode DOWN: " + df.format(d));
    
    df.setRoundingMode(RoundingMode.CEILING);
    System.out.println("Using Rounding mode CEILING: " + df.format(d));```
4. 用`Precision` class
```java
Double d = 456.98234;
Double n = Precision.round(d,2);

5.` Math.round()

a
Double d = 123.4567
d = (double) (Math.round(n*1000.0)/1000.0);
System.out.println(d); // 123.457

# Solution example

a
public static void plusMinus(List<Integer> arr) {
        int positive = 0;
        int negative = 0;
        int zero = 0;
        for(int num : arr){
            if(num == 0){
                zero += 1;
            } else if (num > 0){
                positive += 1;
            } else {
                negative += 1;
            }
        }
        
        float calPos = (float) positive/arr.size();
        float calNeg = (float) negative/arr.size();
        float calZero = (float) zero/arr.size();
        
        
        System.out.println(String.format("%.6f", calPos));
        System.out.println(String.format("%.6f", calNeg));
        System.out.print(String.format("%.6f", calZero));
    }
}```