0

可能重复:
在 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!
4

1 回答 1

2

您输入了字符串"yes",但随后您只从该字符串中读取了一个字符,并留"es"在了输入中。然后尝试通过scanf调用读取它,因为它不是一个数字,所以它会失败,将字母留在输入缓冲区中。

于 2013-02-01T22:39:56.830 回答