请写出Java方法,帮助农民实现如下规划资金使用方法的功能:假设某苗木培育基地有且仅有如下三种果苗:1年果苗1元每棵、3年果苗3元每棵、5年果苗5元每棵;农民有资金X元,期望能够尽量买大龄果苗。请写一段程序
时间: 2024-05-07 11:24:01 浏览: 12
来实现如下功能:输入资金X,输出所能购买的最大龄果苗数量以及剩余资金。
这是一个简单的Java方法来实现上述规划资金使用方法的功能:
```
public static void planFunds(double funds) {
int maxAge = 0;
int numTrees = 0;
while (funds >= 5) {
maxAge = 5;
funds -= 5;
numTrees++;
}
while (funds >= 3) {
maxAge = 3;
funds -= 3;
numTrees++;
}
while (funds >= 1) {
maxAge = 1;
funds -= 1;
numTrees++;
}
System.out.println("购买了 " + numTrees + " 棵 " + maxAge + " 年龄的果苗。剩余资金为 " + funds + " 元。");
}
```
使用该方法,只需传入农民的资金量,即可得到所购买的最大龄果苗数量以及剩余资金,例如:
```
planFunds(10); // 输出:购买了 7 棵 1 年龄的果苗。剩余资金为 0.0 元。
planFunds(20); // 输出:购买了 15 棵 5 年龄的果苗。剩余资金为 1.0 元。
```