Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中时,Do中的无限循环_C_Loops_Do While - Fatal编程技术网

在C中时,Do中的无限循环

在C中时,Do中的无限循环,c,loops,do-while,C,Loops,Do While,我是C语言的新手。我试图用do while循环编写一个简单的程序。程序应该接受整数输入并打印出它的平方。然后询问用户是否继续。如果输入为“y”或“y”,它将继续下一轮,否则退出循环。此外,还有一个子句用于检查除“y”、“y”、“n”、“n”之外的输入。如果是这样,它将重复提示以请求正确的输入 这是我的密码- #include <stdio.h> #include <stdlib.h> int main() { int num; char choice; ch

我是C语言的新手。我试图用do while循环编写一个简单的程序。程序应该接受整数输入并打印出它的平方。然后询问用户是否继续。如果输入为“y”或“y”,它将继续下一轮,否则退出循环。此外,还有一个子句用于检查除“y”、“y”、“n”、“n”之外的输入。如果是这样,它将重复提示以请求正确的输入

这是我的密码-

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

int main()
{
  int num;
  char choice;
  char c;

  system("clear");
  do{
    printf("\nEnter a number: ");
    fflush(stdin);
    scanf("%d", &num);
    printf("Square of %d : %d", num, num*num);
    printf("\n\n");
    getchar();
    do{
      printf("Do you want to continue?(y/n): ");
      scanf("%c", &choice);
      getchar();
      if(choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N'){
        printf("\nInvalid Choice !! Press 'Y/y' or 'N/n'!!\n\n");
      }
    }while(choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N');
  }while(choice == 'y' || choice == 'Y');

  getchar();
  printf("\n\n");
  return 0;
}
#包括
#包括
int main()
{
int-num;
字符选择;
字符c;
系统(“清除”);
做{
printf(“\n输入一个数字:”);
fflush(stdin);
scanf(“%d”和&num);
printf(“%d的平方:%d”,num,num*num);
printf(“\n\n”);
getchar();
做{
printf(“您想继续吗?(是/否):”;
scanf(“%c”,选择(&c));
getchar();
如果(选择!=“y”|选择!=“y”|选择!=“n”|选择!=“n”){
printf(“\N无效选择!!按'Y/Y'或'N/N'!!\N\N”);
}
}while(choice!=“y”| choice!=“y”| choice!=“n”| choice!=“n”);
}while(choice='y'| choice='y');
getchar();
printf(“\n\n”);
返回0;
}

我可以看到两个问题

选择!='选择Y'
将始终计算为true。更改为
choice!='y'&选择!='Y'

fflush(stdin)
是未定义的行为


您还应该检查输入函数的返回值是否有错误。

您的问题中没有问题。更正了代码。不管怎样,正如前面我只检查了choice='y'来提供一个,说明你给程序演示问题的输入,你从程序得到的输出,以及你期望从程序得到的输出。并编辑帖子以提问。比如“为什么这个程序做X而不是Y?”