본문 바로가기

Programming language/C++

[C++] 단위 변환기 소스코드

C++에서 단위 변환기를 만들려면 다양한 측정 단위에 대한 변환 함수를 정의해야 합니다. 다음은 미터, 피트, 인치 등 서로 다른 길이 단위를 변환하는 단위 변환기의 간단한 예입니다.

#include <iostream>
#include <iomanip>
using namespace std;

double metersToFeet(double meters) {
    return meters * 3.28084;
}

double metersToInches(double meters) {
    return meters * 39.3701;
}

int main() {
    cout << "Unit Converter - Length" << endl;
    cout << "1. Meters to Feet" << endl;
    cout << "2. Meters to Inches" << endl;
    cout << "Enter your choice (1 or 2): ";
    
    int choice;
    cin >> choice;

    if (choice != 1 && choice != 2) {
        cout << "Invalid choice. Please choose 1 or 2." << endl;
        return 1; // Exit with an error code
    }

    double input;
    cout << "Enter the value to convert: ";
    cin >> input;

    double result;
    if (choice == 1) {
        result = metersToFeet(input);
        cout << fixed << setprecision(2) << input << " meters is equal to " << result << " feet." << endl;
    } else {
        result = metersToInches(input);
        cout << fixed << setprecision(2) << input << " meters is equal to " << result << " inches." << endl;
    }

    return 0; // Exit successfully
}

실행 방법

1. 프로그램은 사용자에게 미터를 피트로 또는 미터를 인치로 변환하는 두 가지 변환 옵션 중에서 선택하라는 메시지를 표시합니다.
2. 사용자는 선택 사항과 변환할 값을 입력합니다.
3. 사용자의 선택에 따라 적절한 변환 함수가 호출됩니다.
4. 결과는 소수점 이하 두 자리의 정밀도로 표시됩니다.

 

출력 결과

Unit Converter - Length
1. Meters to Feet
2. Meters to Inches
Enter your choice (1 or 2): 1
Enter the value to convert: 5
5.00 meters is equal to 16.40 feet.

 

'Programming language > C++' 카테고리의 다른 글

[C++] 기본 체스 게임 소스 코드  (1) 2023.10.07
[C++] 단어 카운터 구현  (0) 2023.10.07
[C++] 알람시계 구현하기  (0) 2023.10.07
[C++] 텍스트 기반 RPG 구현하기  (0) 2023.10.06
[C++] 온도 변환기 구현  (0) 2023.10.06