算法-->穷举算法

来源:互联网 发布:软考程序员通道 编辑:程序博客网 时间:2024/05/29 14:15

package 穷举算法;

import java.util.Scanner;public class QiongJu {static int chicken,habbit;//分别代表鸡的个数,兔子的个数                 /*穷举算法*/public static int qiongju(int head,int  foot) {int r,i,j;r=0;for(i=0;i<=head;i++) {    j=head-i;    if(i*2+j*4==foot) {        r=1;        chicken=i;        habbit=j;    }}return r;}    public static void main(String []args) {        int r,head,foot;        System.out.println("穷举 发 解决 鸡兔同笼问题");        System.out.println("请输入头数");        Scanner sc=new Scanner(System.in);        head=sc.nextInt();        System.out.println("请输入脚数");        foot=sc.nextInt();        r= qiongju(head,foot);        if(r==1) {            System.out.println("鸡有 "+chicken+"只,兔子"+habbit+"只");        }else {            System.out.println("无法求解");        }    }}

这里写图片描述