Java语言如何解决母鸡下蛋,有一只母鸡第一天下1个蛋第二天下2个蛋,第三天下3个蛋,求第n天一共下几个蛋,用函数怎么解决呢
如图
代码如下
public class Main {
public static void main(String[] args) {
int n = 5; // 第n天
int totalEggs = calculateEggs(n);
System.out.println("第 " + n + " 天共下了 " + totalEggs + " 个蛋。");
}
public static int calculateEggs(int n) {
int totalEggs = 0;
for (int i = 1; i <= n; i++) {
totalEggs += i;
}
return totalEggs;
}
}
不知道你这个问题是否已经解决, 如果还没有解决的话:/**
* 根据给定的天数,计算母鸡一共下了多少个蛋
* @param days 给定的天数
* @return 第n天一共下了多少个蛋
*/
public int calculateEggs(int days) {
if (days < 1) {
throw new IllegalArgumentException("天数必须大于等于1");
}
int totalEggs = 0;
for (int i = 1; i <= days; i++) {
totalEggs += i;
}
return totalEggs;
}
这个解决方案是一个简单的循环,从第1天到第n天,每一天的蛋数逐个累加。注意,这个解决方案假设天数days
一定要大于等于1,否则将抛出一个异常。
使用示例:
int eggs = calculateEggs(5);
System.out.println("第5天一共下了" + eggs + "个蛋");
输出:
第5天一共下了15个蛋
要解决这个问题,使用一个函数来计算第n天母鸡下的总蛋数。
public class Main {
public static void main(String[] args) {
int n = 5; // 第n天
int totalEggs = calculateTotalEggs(n);
System.out.println("第" + n + "天一共下了" + totalEggs + "个蛋");
}
public static int calculateTotalEggs(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i; // 第i天下的蛋数为i个
}
return total;
}
}
代码中,main 函数为程序的入口,调用 calculateTotalEggs 函数来计算第n天母鸡下的总蛋数。
在 calculateTotalEggs 函数内部,使用一个循环来遍历从第1天到第n天的每一天,累加每一天下的蛋数。第i天下的蛋数为i个,因此将i添加到总数中。
最后,输出第n天下的总蛋数。
例如,运行上述代码,并设置n为5,将输出"第5天一共下了15个蛋",表示第5天母鸡下了15个蛋。