소개
이 랩에서는 C++ 프로그래밍 언어를 사용하여 주어진 숫자의 역수를 구하는 방법을 배웁니다. 입력된 숫자의 역수를 구하는 개념은 회문 (Palindrome) 을 확인하는 데 사용될 수 있습니다.
C++ 소스 파일 생성
먼저, ~/project 디렉토리에 C++ 소스 파일을 생성해야 합니다. 터미널을 열고 아래 명령을 입력하여 main.cpp라는 파일을 생성합니다.
touch ~/project/main.cpp
그런 다음 텍스트 편집기를 사용하여 main.cpp 파일을 편집합니다.
C++ 코드 작성
main.cpp 파일에 다음 코드를 추가하여 주어진 숫자의 역수를 구합니다.
#include <iostream>
#include <math.h>
using namespace std;
//Returns the reverse of the entered number
int findReverse(int n)
{
int reverse = 0; //to store the reverse of the given number
int remainder = 0;
//logic to compute the reverse of a number
while (n != 0)
{
remainder = n % 10; //store the digit at the units place
reverse = reverse * 10 + remainder;
n /= 10;
}
return reverse;
}
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to compute the Reverse of the entered number. ===== \n\n";
//variable declaration
int n;
int reverse = 0;
//taking input from the command line (user)
cout << " Enter a positive integer to find the reverse of : ";
cin >> n;
//Calling a method that returns the reverse of an entered number
reverse = findReverse(n);
cout << "\n\nThe entered number is " << n << " and it's reverse is :" << reverse;
cout << "\n\n\n";
return 0;
}
이 코드 조각은 findReverse와 main 두 개의 함수를 정의합니다. findReverse는 임의의 정수를 인수로 받아 역수를 반환합니다. main은 프로그램의 주 함수로, 사용자로부터 입력을 받아 findReverse를 호출하여 역수를 반환합니다.
C++ 코드 컴파일 및 실행
프로그램을 컴파일하고 실행하려면 터미널에 다음 명령을 입력합니다.
g++ ~/project/main.cpp -o ~/project/main && ~/project/main
요약
이 랩에서는 C++ 프로그래밍 언어를 사용하여 주어진 숫자의 역수를 구하는 방법을 배웠습니다. 이 개념은 회문 (Palindrome) 을 확인하는 데 사용될 수 있습니다. 루프를 사용하여 주어진 정수의 각 숫자를 분해하고 역순으로 정렬하여 최종 역수 값을 찾을 수 있습니다. 또한 이 C++ 프로그램을 컴파일, 실행 및 테스트하는 방법도 배웠습니다.



