新手菜鸟编程求助,鸡兔同笼问题!
是这样的,有一道题,说是“百钱买百鸡”,5文钱可以买一只公鸡,3文钱买一只母鸡,1文钱买3只雏鸡,现在用100文钱买一百只鸡,那么各有公鸡母鸡雏鸡各多少只?
public class HowManyChickens { public static void main(String[] args) { final int CHICKEN_NUMBER = 100; final int MONEY_NUMBER = 100; for (int cockNumber = 0; cockNumber < CHICKEN_NUMBER / 5 + 1; cockNumber++) { for (int henNumber = 0; henNumber < CHICKEN_NUMBER / 3 + 1; henNumber++) { for (int chikenNumber = 0; chikenNumber < CHICKEN_NUMBER; chikenNumber++) { if (cockNumber + henNumber + chikenNumber == CHICKEN_NUMBER && cockNumber * 5 + henNumber * 3 + chikenNumber / 3 == MONEY_NUMBER && chikenNumber % 3 == 0) { System.out.println(cockNumber + " " + henNumber + " " + chikenNumber); } } } } } }
public class HowManyChickens2Loops { public static void main(String[] args) { final int CHICKEN_NUMBER = 100; final int MONEY_NUMBER = 100; for (int cockNumber = 0; cockNumber < CHICKEN_NUMBER / 5 + 1; cockNumber++) { for (int henNumber = 0; henNumber < CHICKEN_NUMBER / 3 + 1; henNumber++) { int chikenNumber = CHICKEN_NUMBER - cockNumber - henNumber; if (cockNumber * 5 + henNumber * 3 + chikenNumber / 3 == MONEY_NUMBER && chikenNumber % 3 == 0) { System.out.println(cockNumber + " " + henNumber + " " + chikenNumber); } } } } }