C의 모듈로 연산자

Jinku Hu 2023년10월12일 C C Math
  1. %모듈로 연산자를 사용하여 C의 나눗셈에서 나머지 계산
  2. %모듈로 연산자를 사용하여 C에서 윤년 검사 기능 구현
  3. %모듈로 연산자를 사용하여 C에서 주어진 정수 범위의 난수 생성
C의 모듈로 연산자

이 기사에서는 C에서 모듈로 연산자를 사용하는 방법에 대한 여러 가지 방법을 보여줍니다.

%모듈로 연산자를 사용하여 C의 나눗셈에서 나머지 계산

모듈로 %는 C 언어의 이진 산술 연산자 중 하나입니다. 주어진 두 숫자를 나눈 후 나머지를 생성합니다. 모듈로 연산자는float 또는double과 같은 부동 소수점 숫자에 적용 할 수 없습니다. 다음 예제 코드에서는%연산자를 사용하여 주어진int 배열의modulus 9 결과를 인쇄하는 가장 간단한 경우를 보여줍니다.

#include <stdio.h> #include <stdlib.h>  int main(void) {  int arr[8] = {10, 24, 17, 35, 65, 89, 55, 77};   for (int i = 0; i < 8; ++i) {  printf("%d/%d yields the remainder of - %d\n", arr[i], 9, arr[i] % 9);  }   exit(EXIT_SUCCESS); } 

출력:

10/9 yields the remainder of - 1 24/9 yields the remainder of - 6 17/9 yields the remainder of - 8 35/9 yields the remainder of - 8 65/9 yields the remainder of - 2 89/9 yields the remainder of - 8 55/9 yields the remainder of - 1 77/9 yields the remainder of - 5 

%모듈로 연산자를 사용하여 C에서 윤년 검사 기능 구현

또는%연산자를 사용하여 더 복잡한 함수를 구현할 수 있습니다. 다음 예제 코드는 주어진 연도가 윤인지 아닌지를 확인하는isLeapYear 부울 함수를 보여줍니다. 값이 4로 나눌 수 있지만 100으로 나눌 수없는 경우 1 년은 윤년으로 간주됩니다. 또한 연도 값이 400으로 나눌 수 있으면 윤년입니다.

#include <stdbool.h> #include <stdio.h> #include <stdlib.h>  bool isLeapYear(int year) {  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)  return true;  else  return false; }  int main(void) {  uint year = 2021;  isLeapYear(year) ? printf("%d is leap\n", year)  : printf("%d is not leap\n", year);   exit(EXIT_SUCCESS); } 

출력:

2021 is not leap 

%모듈로 연산자를 사용하여 C에서 주어진 정수 범위의 난수 생성

모듈로 연산자의 또 다른 유용한 기능은 난수 생성 과정에서 숫자의 상위 층을 제한하는 것입니다. 즉, 임의의 정수를 생성하는 함수가 있다고 가정합니다. 이 경우 반환 된 숫자와 최대 값 (다음 예제에서 MAX매크로로 정의 됨)이 필요한 값 사이의 나머지 부분을 취할 수 있습니다. 난수 생성을 위해srandrand 함수를 사용하는 것은 강력한 방법이 아니며 양질의 난수가 필요한 응용 프로그램은 다른 기능을 사용해야합니다.

#include <stdio.h> #include <stdlib.h> #include <time.h>  #define COUNT 10 #define MAX 100  int main(void) {  srand(time(NULL));  for (int i = 0; i < COUNT; i++) {  printf("%d, ", rand() % MAX);  }  printf("\b\b \n");   exit(EXIT_SUCCESS); } 

출력:

3, 76, 74, 93, 51, 65, 76, 31, 61, 97 
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C Math