문제

두 값을 입력 받아 두수의 사이 값들의 합을 출력하도록 프로그램하세요.

('Reference'를 이용하여 프로그램하세요)

 

 

결과물

 

 

해설

10과 20을 받으면 그대로 더하고,

20과 10을 받으면 swap 함수를 사용하도록 하였습니다.

 

 

소스

/*
만든이 : NoSyu
만든 날짜 : 2008-09-14

프로그램 설명
문제3.  두  값을 입력 받아 두수의 사이 값들의 합을 출력하도록 프로그램하세요.
('Reference'를 이용하여 프로그램하세요)
*/

#include <iostream> // iostream include

// using standard input/ouput
using std::cout;
using std::cin;
using std::endl;

// function declaration
void swap(int &a, int &b); // call-by-reference using reference variable swap function

// main function
int main(void)
{
    int val1, val2; // input value.
    int& ref1 = val1; // reference value.
    int& ref2 = val2; // reference value.
    int sum = 0; // 총합

    // 첫번째 값 입력 받음
    cout << "insert input value01: ";
    cin >> ref1;

    // 두번째 값 입력 받음
    cout << "insert input value02: ";
    cin >> ref2;

    // 만약 ref1이 ref2보다 크다면 이 둘의 값을 바꾼다.
    if(ref1 > ref2)
    {
        swap(ref1, ref2); // call swap function
    }

    // ref1부터 1씩 증가하며 ref2까지 더한다.
    for(; ref1 <= ref2; ref1++)
    {
        sum += ref1; // sum 더하기
    }

    // 총합 출력
    cout << "sum : " << sum << endl;

    return 0; // 종료~
}

// call-by-reference using reference variable swap function
void swap(int &a, int &b)
{
    int temp;

    temp = a;
    a = b;
    b = temp;
}

크리에이티브 커먼즈 라이선스
Creative Commons License

글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.

트랙백 주소 :: http://nosyu.pe.kr/trackback/1692

댓글을 달아 주세요

[로그인][오픈아이디란?]