2017-02-12 104 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