C中简单程序的奇怪输出

时间:2013-02-01 22:36:36

标签: c

  

可能重复:
  Debugging code in C

有人可以告诉我我的代码有什么问题,以及它产生这个输出的原因。一旦我输入“是”,输出就变得怪异......我希望我的代码能够正确地用于Y / y和N / n ...但是我的代码中输入的任何其他内容我希望它说“输入无效。请尝试再次。”有人可以编辑我的代码,这样做。

代码:

int main(){
  unsigned num;
  char response;

  do{
     printf("Please enter a positive integer greater than 1 and less than 2000: ");
     scanf("%d", &num);
     if (num > 1 && num < 2000){
        printf("All the prime factors of %d are given below: \n", num);
        printPrimeFactors(num);
        printf("\n\nThe distinct prime factors of %d are given below: \n", num);
        printDistinctPrimeFactors(num);
     }
     else{
        printf("\nSorry that number does not fall between 1 and 2000.\n");
     }
     printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
     getchar();
     response = getchar();
  }
 while(response == 'Y' || response == 'y'); // if response is Y or y then program runs again
 printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
 return 0;
}

输出:

Please enter a positive integer greater than 1 and less than 2000: 1600
All the prime factors of 1600 are given below:
2 2 2 2 2 2 5 5

The distinct prime factors of 1600 are given below:
2 5

Do you want to try another number? Say Y(es) or N(o): yes
Please enter a positive integer greater than 1 and less than 2000: All the prime factors of 1600 are given below:
2 2 2 2 2 2 5 5

The distinct prime factors of 1600 are given below:
2 5

Do you want to try another number? Say Y(es) or N(o): Thank you for using my program. Good  Bye!

1 个答案:

答案 0 :(得分:2)

您输入字符串"yes",但之后只读取该字符串中的单个字符,并在输入中保留"es"。然后尝试通过scanf调用读取它,因为它不是数字,它将失败,使字母仍在输入缓冲区中。