0
public class Solution {
    public static void main(String[] args) {
        int ne = 0;
        int p = 0;
        int z = 0;
        Scanner in = new Scanner(System.in);
        int n = in .nextInt();
        int arr[] = new int[n];
        for (int arr_i = 0; arr_i < n; arr_i++) {
            arr[arr_i] = in .nextInt();
        }
        for (int arr_i = 0; arr_i < n; arr_i++) {
            if (arr[arr_i] > 0) {
                p++;
            } else if (arr[arr_i] < 0) {
                ne++;
            } else {
                z++;
            }
        }
        double n1 = p / n; // this is showing 0 ouput    
        double n2 = ne / n; // this is showing 0 ouput      
        double n3 = z / n; // this is showing 0 ouput    
        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);
    }
}

question is to print the fraction of positive ,negative and zeros to the number of elements in array. the output is showing 0 for everything plz suggest the mistake

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21

2 Answers2

2

Use the code below. You're doing integer division, which rounds the result down to 0.

double n1=((double)p)/n;    
double n2=((double)ne)/n;      
double n3=((double)z)/n;
uoyilmaz
  • 3,035
  • 14
  • 25
0

Java 8 solution:

    AtomicInteger countPositive=new AtomicInteger();
    AtomicInteger countNegative = new AtomicInteger();
    AtomicInteger countZeros = new AtomicInteger();
    AtomicInteger countTotal = new AtomicInteger();


    int[] arr = {-1,-1,0,1,1};
    Arrays.stream(arr).forEach(x->{
        if(x>0){
            countPositive.getAndIncrement();
        } else if(x==0){
            countZeros.getAndIncrement();
        }else{
            countNegative.getAndIncrement();
        }
        countTotal.getAndIncrement();
    });

    System.out.println(new BigDecimal(countPositive.doubleValue()/countTotal.doubleValue()).setScale(6,BigDecimal.ROUND_HALF_EVEN));
    System.out.println(new BigDecimal(countNegative.doubleValue()/countTotal.doubleValue()).setScale(6,BigDecimal.ROUND_HALF_EVEN));
    System.out.println(new BigDecimal(countZeros.doubleValue()/countTotal.doubleValue()).setScale(6,BigDecimal.ROUND_HALF_EVEN));

Using atomicIntegers is necessary because Streams will not allow to modify local variables outside its scope if they are not enforced final. AtomicInteger ensures it is threadsafe when we increment and decrement.

Also, I computed countTotal while I am looping to get individual counts. You can do array.length, there will not be any cost to compute length as JVMs know the value as it is not changing.

Prashant
  • 11
  • 2