
正文
JAVA中守株待兔源代码 编写守株待兔
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
用JAVA代码写出,棚内有鸡和免,用户输入头和脚步的数量,输出鸡和兔的数量 求救
import java.util.Scanner;
public class Test {
public static void main(String[] args){
while(true){
Scanner scanner = new Scanner(System.in);
System.out.println("请分别输入头的数量和脚的数量,用空格分开:");
System.out.println("输入其它内容结束程序运行");
int heads,feet;
try{
heads = scanner.nextInt();
feet = scanner.nextInt();
}catch(Exception e){
break;
}
caculate(heads,feet);
}
}
public static void caculate(int head, int foot){
if((foot(int)1) != 0){
System.out.println("请输入偶数只脚");
return;
}
if(foot 0){
System.out.println("脚数应为非负整数");
return;
}
if(head 0){
System.out.println("头数应为非负整数");
return;
}
if(2*head foot){
System.out.println("头的数量太多");
return;
}
if(4*head foot){
System.out.println("脚的数量太多");
return;
}
int che = (4*head-foot)/2;
int rub = (foot - 2*head)/2;
System.out.println("棚内有" + che + "只鸡和" + rub + "只兔子");
}
}
相关问答
Q1: Java代码编程 经典的兔子问题?
这是斐波那契数列的问题
可以用递归,也可以用循环
递归:
public class Demo3 {
// 使用递归方法
private static int getFibo(int i) {
if (i == 1 || i == 2)
return 1;
else
return getFibo(i - 1) + getFibo(i - 2);
}
public static void main(String[] args) {
System.out.println("斐波那契数列的前20项为:");
for (int j = 1; j = 20; j++) {
System.out.print(getFibo(j) + "\t");
if (j % 5 == 0)
System.out.println();
}
}
}
循环:
public class Demo2 {
// 定义数组方法
public static void main(String[] args) {
int arr[] = new int[20];
arr[0] = arr[1] = 1;
for (int i = 2; i arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
System.out.println("斐波那契数列的前20项如下所示:");
for (int i = 0; i arr.length; i++) {
if (i % 5 == 0)
System.out.println();
System.out.print(arr[i] + "\t");
}
}
}
Q2: 用java怎么实现鸡兔同笼的问题
以“今有雉兔同笼JAVA中守株待兔源代码,上有三十五头JAVA中守株待兔源代码,下有九十四足JAVA中守株待兔源代码,问雉兔各几何JAVA中守株待兔源代码?”为例
public class test {
public static void main(String[] args) {
int x,y; //xJAVA中守株待兔源代码:鸡 y:兔
for(x=0;x=35;x++) { //遍历鸡的只数
y=35-x; //兔的只数等于35 - 鸡
if(2*x+4*y==94) //如果鸡和兔的脚总数是94
System.out.println("鸡"+x+"只,兔"+y+"只");
}
}
}
JAVA中守株待兔源代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于编写守株待兔、JAVA中守株待兔源代码的信息别忘了在本站进行查找喔。






