RatioSomething

This commit is contained in:
Sami 2024-10-21 12:41:23 -04:00
parent 0346f8e0be
commit 317ce9d5b1
2 changed files with 60 additions and 0 deletions

BIN
RatioArray.class Normal file

Binary file not shown.

60
RatioArray.java Normal file
View File

@ -0,0 +1,60 @@
import java.text.DecimalFormat;
/**
* RatioArray
*/
public class RatioArray {
// 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
//
public static void main(String[] args) {
int[] ar = { 1, 1, 0, -1, -1 };
Ratio(ar);
}
private static void Ratio(int[] arr) {
int n = arr.length;
System.out.println("the length of the arr is: " + n);
float pos = 0;
float neg = 0;
float zero = 0;
for (int x : arr) {
if (x > 0) {
pos++;
} else if (x < 0) {
neg++;
} else if (x == 0) {
zero++;
}
}
System.out.println("The number of positive ints in the arr is: " + pos);
System.out.println("The number of negative ints in the arr is: " + neg);
System.out.println("The number of zeros int the arr is: " + zero);
double posRatio = pos / n;
double negRatio = neg / n;
double zeroRatio = zero / n;
System.out.println();
System.out.printf("The ratio of the positive number is: " + "%.6f\n", posRatio);
System.out.printf("The ratio of the positive number is: " + "%.6f\n", negRatio);
System.out.printf("The ratio of the positive number is: " + "%.6f\n", zeroRatio);
}
}