我对C/c++比较陌生,我正在学习嵌套的for循环和数组。我问的问题是指下面的代码
int main(){
int N, M;
bool secret = false;
scanf("%d %d", &N, &M); //N is the amount of weapon "The Hero" has, while M is the amount for "The Villain"
int X[N]; // To store the value of "Damage" each weapon has
int Y[M];
for(int i = 0; i < N; i++){
scanf("%d", &X[i]); // Inputting the value to each weapon
}
for(int i = 0; i < M; i++){
scanf("%d", &Y[i]);
}
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(X[i] > Y[j]){ //To check if atleast one weapon of "The Hero" can beat all the weapon of "The Villain" (What i was trying to do anyways)
secret = true;
} else{
secret = false;
}
}
}
if(secret == true){
printf("The dark secret was truen");
} else{
printf("Secret debunkedn");
}
return 0;
}
我试图检查X数组中是否至少有一个武器的值大于所有的Y数组(而不是Y数组的总和)。我遇到的问题是,如果我将X数组中的最后一个值设置为低于Y数组中的任何一个值,它将始终返回false,并打印出else语句,因为循环将始终到达最后一次迭代并将其用作条件语句。
我原以为结果会是
3 5 // The amount of weapons the Hero and Villain has
4 9 2 // The value of each weapon for the Hero
8 4 6 8 3 // The value of each weapon for the Villain
The dark secret was true // The expected output
换成了
Secret Debunked
,因为循环到X数组中的最后一个值。我试图用break停止if语句,在循环中使用它,两者都没有像预期的那样工作。我想先把它排好,然后用特定的索引来比较。但在尝试之前,我想先在这里问一下。
问题是您总是在内部for循环的每次迭代中设置变量secret
。因此,该变量存储了它的最后一个赋值。
以如下方式重写循环
for ( int i = 0; !secret && i < N; i++ ){
int j = 0;
while ( j < M && X[i] > Y[j] ) j++;
secret = j == M;
}
当你发现hero的值大于villian的值时,打破循环会有帮助
for (int i = 0; !secret && i < N; i++) { // <= secret == true then exit
for (int j = 0; j < M; j++) {
if (X[i] > Y[j]) {
secret = true;
break; // <= found value, no need to check anymore
} else{
secret = false;
}
}
}