凑硬币(标号)
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;}}}}}

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
