簡體   English   中英

要求用戶重復程序或退出 C

[英]Ask user to repeat the program or exit in C

在這個非常基本的程序中,它要求用戶輸入兩個數字,然后程序會將這些數字相加。 我想在最后詢問用戶他/她是否想再次重復該程序或退出該程序! 例如,如果他/她按 y 程序將要求用戶輸入兩個數字,否則程序將關閉。 怎么做 ?

main(){
float x,y,sum;
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f",sum);
}
main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    scanf (" %c", &ch);
    } while(ch == 'y');
    }

或者你也可以試試這個:

main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    ch = getchar();
    getchar();
    } while(ch == 'y');
    }
int main(void) {
float x,y,sum;
char ch;
do {
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}

這使用了一個do-while循環。 它會一直持續到do-whilewhile條件返回 false。

簡單來說,每當用戶輸入yYwhile循環將返回 true。 因此,它將繼續。

檢查 示例和教程以了解do-while循環。

[在這個程序中,我使用了“goto”語句,因為如果我使用 do while 循環,那么如果我輸入任何沒有“Y 或 y”的內容,那么程序將關閉。為了避免這個問題,我使用了“goto”語句。 1

#include<stdio.h>
int main(){
float x, y, sum;
char ch;
print:
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("\nThe total number is:%.2f\n",sum);
again:
    printf ("\n\t\t\t\t\tDo you want to repeat the operation(Y/N): ");
    scanf (" %c", &ch);

    if(ch == 'y' || ch == 'Y'){
        goto print;
    }
    else if(ch == 'n' || ch == 'N'){
        return 0;
    }
    else{
        printf("\n\t\t\t\t\tPlease enter Yes or NO.\n");
        goto again;
    }
   return 0;}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM