如何在 if 语句中插入 continue 语句

How to insert a continue statement inside an if statement

我的代码如下。我正在使用 C 语言。如果用户键入 Y,我想从头开始重复该操作,但我很困惑如何才能做到这一点。

我试图寻找解决方案,但结果不适合我的程序。

#include <stdio.h>

int main() {

    int A, B;

    char Y, N, C;

    printf ("Enter value 1: ");
    scanf ("%i", &B);
    printf ("\nEnter value 2: ");
    scanf ("%i", &A);
    printf ("= %i", A + B);

    printf ("\n\nAdd again? Y or N\n");
    scanf ("%c", &C);
    if (C == Y) {
//This should contain the code that will repeat the:
        printf ("Enter value 1: ");
        scanf ("%i", &B);
        printf ("\nEnter value 2:
    } else if (C == N)
        printf ("PROGRAM USE ENDED.");
    else
        printf ("Error.");
}

您应该将代码包装在 for 循环中:

#include <stdio.h>

int main() {

    int A, B;
    char Y = 'Y', N = 'N', C;

    for (;;) {     // same as while(1)
        printf("Enter value 1: ");
        if (scanf("%i", &B) != 1)
            break;
        printf("\nEnter value 2: ");
        if (scanf("%i", &A) != 1)
            break;

        printf("%i + %i = %i\n", A, B, A + B);

        printf("\n\nAdd again? Y or N\n");
        // note the initial space to skip the pending newline and other whitespace
        if (scanf(" %c", &C) != 1 || C != Y)
            break;
    }
    printf("PROGRAM USE ENDED.\n");
    return 0;
}

你的程序中有很多错误。 语法错误:请自行解决。 无需将 Y 和 N 声明为字符,您可以直接使用它们,因为它们不存储任何值。 现在,不需要继续你可以使用 while 循环。 我已经解决了你的问题。请看一下

此外,您使用了很多 scanf,因此有一个输入缓冲区,一个简单的解决方案是使用 getchar(),它会占用输入键空间。

#include <stdio.h>

int main()
{
    int A, B;
    char C = 'Y';

    while (C == 'Y')
    {
        printf("Enter value 1: ");
        scanf("%i", &B);
        printf("\nEnter value 2");
        scanf("%i", &A);
        printf("= %i\n", A + B);
        getchar();
        printf("\n\nAdd again? Y or N\n");
        scanf("%c", &C);
    }
    if (C == 'N')
    {
        printf("PROGRAM USE ENDED.");
    }
    else
    {
        printf("Error.");
    }
}