close
標題:

while +if (c program)

免費註冊體驗

 

此文章來自奇摩知識+如有不便請留言告知

發問:

#includevoid main(){int x;int i=1;int k=1;printf(" enter a power\n");scanf("%d" , &x);while(i<=x)if (x>=0){i++;k=k*2; }elseprintf("it is not a non negative number");printf("%d\n" ,k);}... 顯示更多 #include void main() { int x; int i=1; int k=1; printf(" enter a power\n"); scanf("%d" , &x); while(i<=x) if (x>=0) { i++; k=k*2; } else printf("it is not a non negative number"); printf("%d\n" ,k); } 當我打-1,我想佢出it is not a non negative number,但唔知點解會出1 跟住我將while(i<=x)同if (x>=0)倒轉,佢就出it is not a non negative number1 點解兩者倒轉會唔同? 仲有有冇方法連1都delete埋,我完全唔知個1係點黎?同while有關?

最佳解答:

我估係因為::: #include void main(){ /*係前面*/ int x; /*打D空格*/ int i=1; /*,方便認.*/ int k=1; printf(" enter a power\n"); scanf("%d" , &x); if (x>=0){ // 加番"{"同"}",你就會更了解程式 while(i<=x){ //if (x>=0){ 擺錯位!!! i++; k=k*2; } printf("%d\n" ,k); }else{ printf("it is not a non negative number"); } //printf("%d\n" ,k); 擺錯位!!! } 兩者倒轉會唔同係當然的!!! While 係 loop. 即係一件事做好多次 if係只做一次 例子: ...... int c = 0; while( c < 10 ){ if( c == 5 ){ cout<<"ha ha ha"<<","; //同printf一樣 }else{ cout<
其他解答:

出多左個 1 係正常, 因為這句「printf("it is not a non negative number");」欠缺「\n」 令程式在下次列印時不會開新行 然後緊隨尾的有句 「printf("%d\n" ,k);」 令程式列印 k 的值,而 k 在初始化時被 set 做 1 因此就會得出 「it is not a non negative number1」 你應該要把列印 k 的編碼搬回 while loop 中 理論上,問題將會解決 其實你可以在程式左邊加上 Break Point 然後按 F5 執行 Debug,程式會在 Break Point 等下 然後按 F10 就會往下一行,F11 跳進 Function 中 逐句行,看看程式的走勢,找出錯誤的原因,這才是程式員 另外,你的程式有改進的空間 如用家輸入錯誤後,是否應該可重新輸入呢? 成功完成一次 Loop 後,可否再輸入數字找出答案呢? 很少程式會只行一次,應該是有一個 Loop,不停地行 直至某一個條件成立後才離開程式,我們稱它為「Main Loop」 方法很簡單,只是在「printf(" enter a power\n");」之前 加多一個 While Loop,自設一個數值是離開的條件,如 -999 while( x != -999 ) {} 盡量令程式容易令User明白如何使用 亦盡量要方便User使用 如做得到,我們稱之為 User Friendly 你的答案: void main() { int x; int i=1; int k=1; printf( "please enter a number : " ); scanf( "%d" , x); if( x > 0 ) { while( i
arrow
arrow

    gpjqem1 發表在 痞客邦 留言(0) 人氣()