用java语言设计循环结构,计算一百块钱买一百只鸡问题。公鸡5元1只, 母鸡3元1只,小鸡1元3只,
用java语言设计循环结构,计算一百块钱买一百只鸡问题。公鸡5元1只,母鸡3元1只,小鸡1元3只,100元钱买100只鸡,公鸡、母鸡、小鸡各能买多少只?跪求各位大神解答!...
用java语言设计循环结构,计算一百块钱买一百只鸡问题。公鸡5元1只,母鸡3元1只,小鸡1元3只,100元钱买100只鸡,公鸡、母鸡、小鸡各能买多少只? 跪求各位大神解答!!!
展开
1个回答
展开全部
brutal force(野蛮算法)强行解:
package testProject;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static final int CHICKEN_NUM = 100;
public static final int FUND_TOTAL = 100;
public static final int COCK_PRICE = 5;
public static final int HEN_PRICE = 3;
public static final int NUM_CHICK_PER_DOLLAR = 3;
public static void main(String args[]){
List<ResultSet> result = new LinkedList<ResultSet>();
int maxCockNum = FUND_TOTAL/COCK_PRICE;
int maxHenNum = FUND_TOTAL/HEN_PRICE;
for(int cockNum=0; cockNum <= maxCockNum; cockNum++){
for(int henNum=0; henNum <= maxHenNum; henNum++){
int remainingFund = FUND_TOTAL - cockNum*COCK_PRICE - henNum*HEN_PRICE;
int chickNum = remainingFund * NUM_CHICK_PER_DOLLAR;
int totalNumOfChicken = cockNum + henNum + chickNum;
if(totalNumOfChicken == CHICKEN_NUM){
ResultSet newSet = new ResultSet(cockNum, henNum, chickNum);
result.add(newSet);
}
}
}
System.out.println("All solutions:");
for(int i=0; i< result.size(); i++){
System.out.println(result.get(i).toString());
}
}
}
class ResultSet{
public ResultSet(int cockNum, int henNum, int chickNum){
this.cockNum = cockNum;
this.henNum = henNum;
this.chickNum = chickNum;
}
@Override
public String toString(){
return "公鸡: "+ cockNum + "只, 母鸡: "+ henNum + "只, 小鸡: " + chickNum + "只.";
}
public int cockNum;
public int henNum;
public int chickNum;
}
==================================
Output:
All solutions:
公鸡: 0只, 母鸡: 25只, 小鸡: 75只.
公鸡: 4只, 母鸡: 18只, 小鸡: 78只.
公鸡: 8只, 母鸡: 11只, 小鸡: 81只.
公鸡: 12只, 母鸡: 4只, 小鸡: 84只.
==================================
追问
请问还有更简单一点的办法吗?有点难懂
追答
This is the only way and pretty easy to understand, u just need some patience to read the code.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询