2017-02-12 108 views
-5

我是C新手,他有一個基本程序,要求用戶輸入一個數字,然後打印這個數字以及它在1-49的範圍。如何用0結束循環?

+3

如果你發佈你的代碼它會更清楚。另外,什麼範圍?如果我輸入'7',那麼你的程序應該做什麼? – asimes

+1

如果您發佈了7,它將打印7並打印另一個語句以顯示它在1-49範圍內。 (如果用戶輸入較大的數字,他們會得到一個聲明,並且程序要求輸入不同的數字。) –

+3

將您的代碼用於獲取其編號並在無限循環內響應消息。當他們進入'0'時打破循環或退出程序 – asimes

回答

1
#include <stdio.h> 

int main() { 
    for (;;) { 
     printf("Enter a number: "); 

     char buf[10]; 
     fgets(buf, 10, stdin); 
     printf("You entered %s\n", buf); 

     // Code for displaying the range 

     if (buf[0] == '0') 
      break; 
    } 

    printf("Outside the loop\n"); 
    return 0; 
} 
+4

討厭迂腐,但是如果你輸入一個像038這樣的0填充的數字,這將失敗。 – faviouz

3
#include <stdlib.h> 
#include <stdio.h> 

int main(int argc, char **argv) 
{ 
    int n; 

    do { 
     // Read the number into n 
     printf("Enter a number: "); 
     if (scanf("%d", &n) != 1) { 
      perror("scanf"); 
      exit(EXIT_FAILURE); 
     } 

     // Check arbitrary condition 
     if (n >= 1 && n <= 49) { 
      printf("%d is in the range 1-49\n", n); 
     } 
    } while (n != 0); 

    return EXIT_SUCCESS; 
} 
+2

好的代碼在使用'n'之前檢查'scanf(「%d」,&n);''''的返回值。 (「%d」,&n)!= 1)Print_Error_and_Exit()' – chux

+0

@chux很好,謝謝! – faviouz

+1

不錯的代碼1+,仍然完整性改變'返回0;'是'return EXIT_SUCCESS;' – alk