1.如何用1元,5元,10元,20元凑出任意的金额
Scanner in = new Scanner(System.in);
int amount = in.nextInt();
for(int one = 0; one<=amount; ++one)
{
for(int five = 0; five<=amount/5; ++five)
{
for(int ten = 0; ten<=amount/10; ++ten)
{
for(int twenty=0; twenty<=amount/20; ++twenty)
{
if(one+five*5+ten*10+twenty*20==amount)
{
System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
}
}
}
}
}
这种算法会得到很多中答案
当我们只需要得到一种答案时
不能只用一个break;break只能跳出它那一层的循环。
法一
(多个break)
Scanner in = new Scanner(System.in);
int amount = in.nextInt();
int isExit = 0;
for(int one = 0; one<=amount; ++one)
{
for(int five = 0; five<=amount/5; ++five)
{
for(int ten = 0; ten<=amount/10; ++ten)
{
for(int twenty=0; twenty<=amount/20; ++twenty)
{
if(one+five*5+ten*10+twenty*20==amount)
{
System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
isExit = 1;
break;
}
}
if(isExit==1) break;
}
if(isExit==1) break;
}
if(isExit==1) break;
法二(标号)
Scanner in = new Scanner(System.in);
int amount = in.nextInt();
OUT:
for(int one = 0; one<=amount; ++one)
{
for(int five = 0; five<=amount/5; ++five)
{
for(int ten = 0; ten<=amount/10; ++ten)
{
for(int twenty=0; twenty<=amount/20; ++twenty)
{
if(one+five*5+ten*10+twenty*20==amount)
{
System.out.println(one+" 1R "+five+" 5R "+ten+" 10R "+twenty+" 20R ");
break OUT;
}
}
}
}
}