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



我的代码如下。我在用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 ("nnAdd again? Y or Nn");
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 = %in", A, B, A + B);
printf("nnAdd again? Y or Nn");
// 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("= %in", A + B);
getchar();
printf("nnAdd again? Y or Nn");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}

最新更新