0

重複の可能性:
C でのコードのデバッグ

誰かが私のコードの何が問題なのか、なぜこの出力が生成されるのか教えてもらえますか? 「yes」と入力すると、出力が奇妙になります...コードが 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"が、その文字列から 1 文字だけを読み取り、"es"入力を残します。これは呼び出しによって読み取られようとしますがscanf、数値ではないため失敗し、文字は入力バッファーに残ります。

于 2013-02-01T22:39:56.830 に答える