//有1分,2分,5分,10分四种硬币,每种硬币数量无限,给定n分钱,求有多少种组合可以组合成n分钱?
public class Test {
public static void main(String[] args) {
int x1,x2,x5,x10;//分别定义1,2,5,10分钱的数量
int sum=0;
Scanner input = new Scanner(System.in);
int n=input.nextInt();//接收输入的n
for(x10=0;x10<=n/10;x10++){
for(x5=0;x5<=(n-x10*10)/5;x5++){
for(x2=0;x2<=(n-x10*10-x5*5)/2;x2++){
for(x1=0;x1<=(n-x10*10-x5*5-x2*2);x1++){
if((x1+2*x2+5*x5+10*x10)==n){
sum++;
}
}
}
}
}
System.out.println("组合共有"+sum+"种");
}
}
第一题把6楼的代码改进了一下,不知道还有没有更高效的,可以分享下。
第二题有空再写了,有点晚了,先睡了
第一个题 for()循环嵌套
import java.util.Scanner;
public class Coin
{
public static void main(String [] args)
{
int sum=0;
System.out.println("Input a number is n:"); //输入一个n的值
Scanner input = new ……
[/Quote]
public class Test {
public static void main(String[] args) {
Set<Person> set = new TreeSet<Person>(new Mycomparator());
Person p1 = new Person(18.1,57.5);
Person p2 = new Person(17.2,56.4);
Person p3 = new Person(18.3,45.5);
Person p4 = new Person(16.5,80.5);
Person p5 = new Person(19.3,60.5);
Person p6 = new Person(19.2,56.0);
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
set.add(p5);
set.add(p6);
for(Iterator ite =set.iterator();ite.hasNext();){
Person p = (Person)ite.next();
System.out.println(p.getHeight());
}
}
}
class Person
{
private double height;
private double weight;
public Person(double height,double weight){
this.height=height;
this.weight=weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
// 自定义的比较器
class Mycomparator implements Comparator{
public int compare(Object o1,Object o2) {
Person p1 =(Person)o1;
Person p2 =(Person)o2;
// 比较只能体重和身高都占优势的时候才能加进去
if(p1.getHeight()>p2.getHeight()&&p1.getWeight()>p2.getWeight()){
return 1;
}else if(p1.getHeight()<p2.getHeight()&&p1.getWeight()<p2.getWeight()){
return 1;
}
return 0;
}