我已经制作了这个计算器。
一切正常。
但是,我想使用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();
}
答案 0 :(得分:0)
您的while循环终止,因为scanf("%c",&cont);
从缓冲区中读取剩余的\n
,导致您的while
语句失败。
您应该将scanf修改为scanf(" %c",&cont);
。
答案 1 :(得分:0)
将scanf
语句置于while循环中,或者您可以使用do..while
循环代替while
。
do {
// code
printf("Do you want to continue (y/n)"); scanf("%c",&cont);
} while(cout=="y");