weixin_42400552 2010-11-30 22:09
浏览 244
已采纳

为什么是死循环??

#include<stdio.h>
main()
{
 int x=0,y=0;
 char i='y',j='\0';
 printf("hello world!\n");
 while(i=='y') 
 {   
    
  printf("enter x and y\nx=");
  scanf("%d",&x);
  printf("y=");
  scanf("%d",&y);
  if (x==y)
   printf("x=y, no maximum.\n");
  else if (x>y)
   printf("x>y, x is the maximum.\n");
  else
   printf("x<y, y is the maximum.\n");  
  printf("enter 'y' or 'Y' to continue.\nand press others to quiet...\nyour choose is...");
  
  scanf("%c",&j);
  if (j=='y')
   i='\0'; 
  printf("\n*************************\n");
   
  
 }
 
}

为什么是死循环??

scanf("%c",&j);

怎么没有执行到??

求解。

  • 写回答

2条回答 默认 最新

  • changzhiwin 2010-12-02 16:07
    关注

    [code="java"]#include
    int main()
    {
    int x=0,y=0;
    char i='y',j='\0';
    printf("hello world!\n");
    while(i=='y')
    {

    printf("enter x and y\nx=");
    scanf("%d",&x);
    getchar();
    printf("y=");
    scanf("%d",&y);
    getchar();
    if (x==y)
    printf("x=y, no maximum.\n");
    else if (x>y)
    printf("x>y, x is the maximum.\n");
    else
    printf("x<y, y is the maximum.\n");

    printf("enter 'y' or 'Y' to continue.\nand press others to quiet...\nyour choose is...");

    scanf("%c",&j);
    getchar();
    if (j != 'y' && j != 'Y')
    i='\0';
    printf("\n*************************\n");

    }

    }
    [/code]
    这样就可以了,原因是scanf过滤空格、制表符、回车,当你输入数字的时候敲了回车。getchar就读到了你最后敲的那个回车符了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?