我的代碼如下。我正在使用 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.");
}
uj5u.com熱心網友回復:
您應該將代碼包裝在一個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;
}
uj5u.com熱心網友回復:
你的程式有很多錯誤。語法錯誤:請自行解決。不需要將 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.");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434834.html
