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 回答