我有我的代碼運行,直到用戶輸入「0 0 0」來停止程序 但我的程序在一個循環後停止。我試圖在內部循環添加打印看什麼值分別爲,也許他們都得到設置0不知道爲什麼它退出循環(在C)
我的示例輸入
輸出
p = 4,S = 9,C = 6
p = 3,S = 6,C = 6
p = 2,S = 4,C = 6
p = 1,S = 0,C = 6
情景#1:MHR乘坐單人騎行線騎4次。
我可以看到,P,S,和C不都是0,所以我不知道爲什麼它擺脫了外循環時,它應該只是回去問了3用戶輸入值
#include <stdio.h>
#include <stdlib.h>
int main(){
int p,s,c,h,x=1,coaster;
while(p != 0 && s != 0 && c != 0){
//number of parties, single riders, capacity of ride
scanf("%d%d%d",&p,&s,&c);
//allocate memory
int* parties = malloc(sizeof(int)*p);
for(h=0;h<p;h++){
//get size of each party in line
scanf("%d",&parties[h]);
}
//find the faster line for each scenario
int t = 0;
while(p != 0 || s > 0){
coaster = c - parties[t];
s = s - coaster;
p--;
printf("p = %d, s = %d, c = %d\n",p,s,c);
if(p == 0 && s != 0){
printf("Scenario #%d: MHR rides coaster #%d, using the regular line.\n",x,t+1);
break;
}
if(s <= 0 && p != 0){
printf("Scenario #%d: MHR rides coaster #%d, using the single rider line.\n",x,t+1);
break;
}
if(s <= 0 && p == 0){
printf("Scenario #%d: MHR rides coaster #%d, using either line.\n",x,t+1);
break;
}
t++;
}
x++;
free(parties);
}
return 0;
}
既然你沒有初始化P,S或C,該程序將立即如果他們退出恰巧最初爲零。此外,你的邏輯似乎是錯誤的 - 如果這些變量中的任何一個都爲零,那麼'(p!= 0 && s!= 0 && c!= 0)將是錯誤的。 –