2016-07-16 57 views
0

嗨,我仍然在學習C,這是我想出的。我的問題是,如果用戶輸入的變量'數字'小於或等於0,它不會開始到開始。任何提示?另外請注意,如果我問,如何在使用函數時循環到開頭?循環到開始

void main() { 

    int x = 0, y = 0, m, n, number, life = 4; 
    char choice; 
    int a[R][C] = { {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0} }; 

    do { 
     printf("\t\t\t  Welcome to my game"); 
     Sleep(2000); 
     printf("\n\n This game is all about guessing where your number is located in the matrix"); 
     Sleep(2000); 
     printf("\n\n\t\t\t\tOnly 1 player\n"); 
     Sleep(2000); 
     printf("\n\n You are betting your own very life! \t\t\tYou have 5 tries"); 
     Sleep(1000); 
     printf("\n\nEnter your number: "); 
     scanf("%d", &number); 
     system("cls"); 
     if (number <= 0) { 
      system("cls"); 
      printf("Only positive numbers allowed"); 
      printf("\nRetry? Y/N: "); 
      fflush(stdin); 
      scanf("%c", &choice); 
      fflush(stdin); 
      if (choice == 'n' || choice == 'N') { 
       system("cls"); 
       printf("Thanks for playing"); 
       break; 
      } 
      system("cls"); 
      break; 
     } 
     display(a); 
     printf("\n\nInputted number is %d", number); 
     printf("\n\nYour number is now being placed at a random location"); 
     printf("\n\nGuess where your number is located (row) (column)"); 
     printf("\n\nNote: Enter only numbers 1-4 or else you'll be wrong"); 
     printf("\n\nEnter coordinates: "); 
     scanf("%d%d", &m, &n); 
     printf("\n"); 
     placingguess(a, number, m, n, life); 
     break; 
    } while (choice != 'n' || choice != 'N'); 

    getch(); 
} 
+3

從技術上講,你在代碼中有未定義的行爲,做'fflush(stdin)'不是一個已定義的操作。一些標準庫允許它作爲擴展,但如果你想編寫可移植的代碼,你不應該習慣這樣做。 –

+1

你真的覺得有關程序睡7000秒嗎?更進一步說,'stdin'上的'fflush'會導致未定義的行爲。什麼是'cls'? – user3078414

+1

至於你的問題,那些在循環中摻雜的break語句是什麼?你*知道什麼['break'](http://en.cppreference.com/w/c/language/break)在一個循環內?' –

回答

3

使用continue而不是break

} 
    system("cls"); 
    continue; 
} 
display(a); 
+0

我從來不知道有一個命令,如'繼續'。現在它工作了!謝謝。 – Steven

2

您已經使用

break; 
  • break - 退出當前while \ for \ do - while ...
  • continue - 下一次迭代。

第一個break;就好了,因爲用戶輸入N重試, 第二個需要是continue

+0

謝謝!現在它正在工作。直到現在,從來不知道有一個命令'繼續'。 – Steven