소개
덧셈, 뺄셈, 곱셈, 나눗셈과 같은 산술 연산은 프로그래밍의 기본적인 연산입니다. 이 랩에서는 기본적인 산술 연산을 수행하는 C 프로그램을 작성하는 방법과 C 언어가 형변환 (typecasting) 을 처리하는 방법을 보여드리겠습니다.
덧셈, 뺄셈, 곱셈, 나눗셈과 같은 산술 연산은 프로그래밍의 기본적인 연산입니다. 이 랩에서는 기본적인 산술 연산을 수행하는 C 프로그램을 작성하는 방법과 C 언어가 형변환 (typecasting) 을 처리하는 방법을 보여드리겠습니다.
시작하기 전에, 컴퓨터에 C 컴파일러가 설치되어 있는지 확인하십시오. 텍스트 편집기를 열고 ~/project/ 디렉토리에 "main.c"라는 새 파일을 만듭니다.
stdio.h 헤더 파일을 포함하고 main 함수를 작성하는 것으로 시작해 보겠습니다.
#include<stdio.h>
int main()
{
return 0;
}
scanf() 함수를 사용하여 사용자에게 두 개의 정수를 입력하도록 요청합니다. 이 정수를 저장할 변수를 int a 및 int b로 선언합니다.
#include<stdio.h>
int main()
{
int a, b;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
return 0;
}
이제 타입 캐스팅 없이 기본 산술 연산을 수행해 보겠습니다. 산술 연산의 결과를 저장할 변수를 add, subtract, multiply, divide로 선언합니다.
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
return 0;
}
C 언어는 타입 캐스팅을 암시적으로 처리합니다. 하지만, 프로그램에서 명시적으로 처리할 수도 있습니다. 타입 캐스팅을 사용하여 기본 산술 연산을 수행하는 C 프로그램을 작성해 보겠습니다.
산술 연산의 결과를 저장할 변수를 add, subtract, multiply, divide, remainder로 선언합니다.
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply, remainder;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / (float)b;
remainder = a % b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
return 0;
}
main.c 파일을 저장합니다. 파일을 저장한 ~/project/ 디렉토리에서 터미널을 열고 다음 명령을 사용하여 프로그램을 컴파일합니다.
gcc -o main main.c
이렇게 하면 main이라는 실행 파일이 생성됩니다. 다음 명령을 사용하여 프로그램을 실행합니다.
./main
두 개의 정수를 입력하여 프로그램이 예상대로 산술 연산을 수행하는지 테스트합니다.
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply, remainder;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / (float)b;
remainder = a % b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
return 0;
}
이번 랩에서는 기본적인 산술 연산을 수행하는 C 프로그램을 작성하는 방법과 C 언어가 타입 캐스팅 (typecasting) 을 처리하는 방법을 배웠습니다. 타입 캐스팅을 사용하거나 사용하지 않고 기본적인 산술 연산을 수행하는 방법을 시연했습니다. 마지막으로, 프로그램의 기능을 테스트하기 위해 프로그램을 컴파일하고 실행했습니다.