我似乎不明白为什么我的for循环不能工作。我已经在网上呆了大约一个小时了,离我最近的就是这个。我正在尝试找出使用6、9和20包可以买到多少McNuggets。我需要dopeChecker(x)做的就是返回true或false。我还没有实现检查下一个数字,因为它甚至不会发现6包还可以购买。我知道它在某个地方,但我就是找不到。这是麻省理工学院公开课的问题2,我不知道你们有没有看过,但我只是想让你们知道,这就是我获取信息的地方。
int x = 0, y = 0, z = 0;// These will the the pack of McNuggets that we can buy.
int testFor = 0; //This will be the number of McNuggets we are looking for.
int matches = 0; //This will be the number of consecutive matches we will be looking for.
public void dopeEquation(){
while (matches < 6){//It's 6 Because that is the smallest order of nuggets we can buy.
//Looking for smaller nuggets then we can buy would not make sense.
while (testFor < 6){
testFor++;
}
if (dopeChecker(testFor)){
matches++;
} else{
matches = 0;
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
}
}
}
private boolean dopeChecker(int testFor){
for ( x = 0 ; x*6 <= testFor; x++){
for ( y = 0 ; y*9 <= testFor; y++){
for (z = 0 ; z*20 <= testFor;){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}
}
}
return false;
}
}发布于 2011-07-20 13:52:32
您的代码放在第一个while循环中:
while (matches < 6){然后使用以下代码将testFor增加到6:
while (testFor < 6){
testFor++;
}然后转到dopeChecker:
dopeChecker(int testFor)然后插入第三个循环,对于z:
for (z = 0 ; z*20 <= testFor;) {
...
}Z永远不会递增,因此您需要将其写为:
for (z = 0 ; z*20 <= testFor; z++){
}发布于 2011-07-20 13:39:05
Z变量始终为0,您不能更改它。
发布于 2011-07-20 13:42:00
下面是最里面的for循环。我已经评论了问题所在。如您所见,z从未实现过。因此,从testFor >= 6开始,循环将永远不会终止,因为0 <= TestFor。
for (z = 0 ; z*20 <= testFor;/* incrementor needed here*/){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}https://stackoverflow.com/questions/6757426
复制相似问题