要求用户重复程序或在C中退出

4nkexdtk  于 2023-01-20  发布在  其他
关注(0)|答案(3)|浏览(66)

在这个非常基本的程序中,要求用户输入两个数字,然后程序会将这些数字相加。我想在最后问用户他/她是否想再次重复程序或退出程序!例如,如果他/她按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);
}
ctzwtxfj

ctzwtxfj1#

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');
    }
093gszye

093gszye2#

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。
简单地说,每当用户输入yY时,while循环将返回true,因此它将继续。
查看do-while循环的this示例和教程。

yjghlzjz

yjghlzjz3#

[In这个程序我使用'后藤'语句是因为如果我使用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;}

相关问题