8

クラス用の単純な C プログラムを作成しようとしていますが、要件の 1 つは、すべての入力と出力にscanf/を使用する必要があることです。printf私の質問はscanf、メインの for ループの後がスキップされ、プログラムが終了するのはなぜですか。

これが私のコードです

#include <stdio.h>

void main() {
    int userValue;
    int x;
    char c;

    printf("Enter a number : ");
    scanf("%d", &userValue);
    printf("The odd prime values are:\n");
    for (x = 3; x <= userValue; x = x + 2) {
        int a;
        a = isPrime(x);
        if (a = 1) { 
            printf("%d is an odd prime\n", x);
        }
    }   
    printf("hit anything to terminate...");
    scanf("%c", &c);    
}

int isPrime(int number) {
    int i;
    for (i = 2; i < number; i++) {
        if (number % i == 0 && i != number)
            return 0;
    }
    return 1;
}

最初のものの後に別の同一のものを追加することでそれを「修正」することができましたscanfが、私はそれを使用したいと思います。

4

1 に答える 1

22

stdin前の が入力された後に に存在する改行文字はint、 への最後の呼び出しによって消費されませんscanf()scanf()そのため、ループ後の呼び出しはfor改行文字を消費し、ユーザーが何も入力しなくても続行します。

scanf()別の呼び出しを追加せずに修正するには、ループ" %c"scanf()後にフォーマット指定子を使用できます。forこれによりscanf()、先頭の空白文字 (改行を含む) がスキップされます。プログラムを終了するには、ユーザーが改行以外の何かを入力する必要があることを意味することに注意してください。

さらに:

  • の結果をチェックしてscanf()、渡された変数に実際に値が割り当てられていることを確認します。

    /* scanf() returns number of assigments made. */
    if (scanf("%d", &userValue) == 1)
    
  • これは代入です (そして常に true になります):

    if (a = 1){ /* Use == for equality check.
                   Note 'a' could be removed entirely and
                   replace with: if (isPrime(x)) */
    
于 2013-01-23T16:29:03.173 に答える