如何使用 while 循环终止程序

How to terminate a program using while loop

我做了这个计算器。

一切正常。

但是,我想按如下方式使用 while 循环:

char cont = 'y'
while (cont == 'y') {
    /code/
}
printf("Do you want to continue (y/n)")
scanf("%c", & cont)

这会打印:

Do you want to continue (y/n)

但是当我输入一些东西时程序意外结束。

完整代码:

#include < stdio.h > 
#include < conio.h >

void main() {
    float x, y, result;
    int select;
    char cont = 'y';
    clrscr();
    while (cont == 'y') {
        clrscr();
        printf(
            "Please Enter The Respective Number For Following Operation\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n"
        );
        scanf("%d", & select);
        clrscr();
        switch (select) {
        case 1:
            {
                printf("\nEnter The First Number To Add\n");
                scanf("%f", & x);
                printf("\nEnter The Second Number To Add\n");
                scanf("%f", & y);
                clrscr();
                result = x + y;
                printf("Addition of two numbers %f and %f is %f", x, y,
                    result);
                break;
            }
        case 2:
            {
                printf("\nEnter The First Number To Subtract\n");
                scanf("%f", & x);
                printf("\nEnter The Second Number To Subtract\n");
                scanf("%f", & y);
                clrscr();
                result = x - y;
                printf("Subtraction of two numbers %f and %f is %f", x, y,
                    result);
                break;
            }
        case 3:
            {
                printf("\nEnter The First Number To Multiply\n");
                scanf("%f", & x);
                printf("\nEnter The Second Number To Multiply\n");
                scanf("%f", & y);
                clrscr();
                result = x * y;
                printf("Multiplication of two numbers %f and %f is %f", x,
                    y, result);
                break;
            }
        case 4:
            {
                printf("\nEnter The Numerator\n");
                scanf("%f", & x);
                printf("\nEnter The Denominator\n");
                scanf("%f", & y);
                clrscr();
                result = x / y;
                printf("\nDivision of two numbers %f and %f is %f", x, y,
                    result);
                break;
            }
        default:
            {
                printf("Invalid Choice");
                break;
            }
        }
        printf("\n\nCalculator By XXX\n\nDo you want to Continue (y/n)\n");
        scanf("%c", & cont);
    }
    getch();
}

您的 while 循环终止,因为 scanf("%c",&cont); 从缓冲区读取剩余的 \n,这使得您的 while 语句失败。 您应该将 scanf 修改为 scanf(" %c",&cont);.

scanf 语句放在 while 循环中,或者您可以使用 do..while 循环代替 while

do { 
   // code
   printf("Do you want to continue (y/n)"); scanf("%c",&cont);

} while(cout=="y");