请设计一个功能类DecimalManager,其中包含对n个数求和,n个数求最大值,最小值的功能。并在main()中对其进行测试。
时间: 2023-05-23 09:05:32 浏览: 85
下面是一个基本的DecimalManager类的设计,包含对n个数求和,n个数求最大值,最小值的功能。在main()中,通过创建DecimalManager对象,并调用其方法来进行测试。
```
public class DecimalManager {
private double[] numbers;
private int count;
public DecimalManager(int n) {
numbers = new double[n];
count = 0;
}
public void addNumber(double num) {
if (count >= numbers.length) {
System.out.println("DecimalManager is full");
return;
}
numbers[count++] = num;
}
public double getSum() {
double sum = 0;
for (int i = 0; i < count; i++) {
sum += numbers[i];
}
return sum;
}
public double getMax() {
if (count == 0) {
return 0;
}
double max = numbers[0];
for (int i = 1; i < count; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
public double getMin() {
if (count == 0) {
return 0;
}
double min = numbers[0];
for (int i = 1; i < count; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
return min;
}
}
```
在main()中的测试如下:
```
public static void main(String[] args) {
DecimalManager decimalManager = new DecimalManager(5);
decimalManager.addNumber(3.14);
decimalManager.addNumber(2.1);
decimalManager.addNumber(-5.5);
decimalManager.addNumber(8.2);
decimalManager.addNumber(0.5);
System.out.println("Sum: " + decimalManager.getSum());
System.out.println("Max: " + decimalManager.getMax());
System.out.println("Min: " + decimalManager.getMin());
}
```
输出:
```
Sum: 8.44
Max: 8.2
Min: -5.5
```
阅读全文