홍정모의 따라하며 배우는 C언어 정리

while 반복 루프에서 scanf()의 반환값 사용하기

채고루 2023. 3. 14. 22:50

위와 같이 결과값이 나오도록 코드짜기

 

#include <stdio.h>
int main(void)
{
  int num, sum = 0;
  int status; // scanf function의 반환값

  printf("Enter an integer (q to quit) : ");
  status = scanf("%d", &num);  // return value of scanf(), 정수가 입력되면 status에 1이라는 값 저장, 
                                                   문자를 입력했으면 정수로 입력을 받을 수 없기 때문에 status에 0이 들어감

  while (status == 1) 
    {
      sum = sum + num; 

      printf("Enter next integer (q to quit) : ");
      status = scanf("%d", &num);

    }

printf("Sum=%d\n", sum);
return 0;

 더 간단하게 코드 작성하기 


int num, sum = 0;

printf("Enter an integer (q to quit) : ");

while (scanf("%d", &num) == 1)    => 함수가 아니라 조건문 안에 넣기

   {  
      sum = sum + num;
      printf("Enter next integer (q to quit) : ");
   }

printf("Sum=%d\n", sum);
return 0;
}

 

<PLUS: 의사 코드 Pseudo Code>
Initalize sum to 0
Prompt user
Read input
While the input is an integer
Add the input to sum
Prompt user
Then read next input
After input complete, print sum

While getting and testing the value succeeds    ->  while (scanf("%d", &num) == 1)  
   Process the value


'홍정모의 따라하며 배우는 C언어 정리' 카테고리의 다른 글

사실과 거짓  (0) 2023.03.15
관계 연산자  (0) 2023.03.14
자료형 변환  (0) 2023.03.14
증가, 감소 연산자  (0) 2023.03.08
연산자 우선순위, 나머지 연산자  (0) 2023.03.06