3

どこで間違ったのかわかりません。秒単位で読み取らずscanf()、次の行にスキップします。

#include <stdio.h>
#define PI 3.14

int main()
{
    int y='y', choice,radius;
    char read_y;
    float area, circum;

do_again:
    printf("Enter the radius for the circle to calculate area and circumfrence \n");
    scanf("%d",&radius);
    area = (float)radius*(float)radius*PI;
    circum = 2*(float)radius*PI;

    printf("The radius of the circle is %d for which the area is %8.4f and circumfrence is %8.4f \n", radius, area, circum);

    printf("Please enter 'y' if you want to do another calculation\n");
    scanf ("%c",&read_y);
    choice=read_y;
    if (choice==y)
        goto do_again;
    else
        printf("good bye");
    return 0;
}
4

2 に答える 2

10

最初の scanf() は入力ストリームに改行を残し、文字を読み取るときに次の scanf() によって消費されます。

変化する

scanf ("%c",&read_y);

scanf (" %c",&read_y); // Notice the whitespace

すべての空白を無視します。


一般に、入力の読み取りに scanf() を使用しないでください (特に、ここで行っているように異なる形式を混在させる場合)。代わりにfgets()を使用し、 sscanf()を使用して解析します。

于 2013-06-19T07:25:23.857 に答える
1

あなたはこれを行うことができます:

#include <stdlib.h>
#define PI 3.14

void clear_buffer( void );

int main()
{
    int y='y',choice,radius;
    char read_y;
    float area, circum;
    do_again:
        printf("Enter the radius for the circle to calculate area and circumfrence \n");        
        scanf("%d",&radius);        
        area = (float)radius*(float)radius*PI;
        circum = 2*(float)radius*PI;    
        printf("The radius of the circle is %d for which the area is %8.4f and circumfrence is %8.4f \n", radius, area, circum);
        printf("Please enter 'y' if you want to do another calculation\n"); 
        clear_buffer();
        scanf("%c",&read_y);            
        choice=read_y;      
    if ( choice==y )
        goto do_again;
    else
        printf("good bye\n");
    return 0;
}

void clear_buffer( void )
{
     int ch;

     while( ( ch = getchar() ) != '\n' && ch != EOF );
}

または、scanf の前に fflush(Stdin) を書くことができます

于 2013-06-19T11:12:44.950 に答える