2017-11-19 14 views
-5

이 계산기를 만들었습니다.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

실제 발생 상황을 이해하기 위해 코드를 디버깅 해 보셨습니까? –

+2

이 코드는 읽을 수 없습니다. 게시하기 전에 포맷을 시도하십시오. –

+0

들여 쓰기/포맷 :( –

답변

0

scanf("%c",&cont);가 실패하여 while 성명을 버퍼에서 남은 \n을 읽기 때문에 귀하의 while 루프가 종료됩니다. scanf를 scanf(" %c",&cont);으로 수정해야합니다.

0

scanf 문을 while 루프에 넣거나 do..while 루프를 while 대신 사용할 수 있습니다.

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

} while(cout=="y");