Debugging code in C

时光毁灭记忆、已成空白 提交于 2019-12-02 15:56:21

问题


Can someone tell me what is wrong with my code and why it is producing this output.

Code:

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;
}

Output:

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:


When you ask whether you want to repeat, you only read the y, leaving the es queued up in stdin. When you go to read the next number, scanf tries to parse that as a number, fails, and returns without altering num. When you prompt the user, you need to burn that whole line.



来源:https://stackoverflow.com/questions/14655427/debugging-code-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!