리눅스를 통하여 Git에 cpp파일을 저장하려한다.

이전에 github을 이용하긴 했었지만 오랜만에 이용하니 처음부터 차근차근

해가는 과정을 보이겠다.

생성

-git 홈페이지에서의 과정

다음과 같이 new repositories에 내가 저장할 저장공간을 만들어준다.

-리눅스에서의 과정

        1-1.working directory(work tree) 생성하기(work tree는 실제 파일들로 이루어진 디렉토리이다.)
        ubuntu@ip-172-31-2-64:~$ mkdir gitit

        1-2.work tree로 이동하기
        ubuntu@ip-172-31-2-64:~$ cd ./gitit/

        1-3.work tree 디렉토리 지정해주기
        ubuntu@ip-172-31-2-64:~/gitit$ git init
        Initialized empty Git repository in /home/ubuntu/gitit/.git/
        ubuntu@ip-172-31-2-64:~/gitit$ git status
        On branch master

        1-4.내가 git에 올려줄 파일을 생성하여주기
        ubuntu@ip-172-31-2-64:~/gitit vi stream.cpp
        <이하 생략>

        git status 명령어를 통하여 index(커밋을 실행하기전 저장소와 작업트리 사이에 존재하는 공간) 확인하기.
        ubuntu@ip-172-31-2-64:~/gittest$ git status

        2-1 인덱스에 등록하여주기
        ubuntu@ip-172-31-2-64:~/gitit$ git add heritance
        ubuntu@ip-172-31-2-64:~/gitit$ git add stream.cpp

        2-2 인덱스 확인하기.
        ubuntu@ip-172-31-2-64:~/gitit$ git status
        On branch master

        Initial commit

        Changes to be committed:
          (use "git rm --cached <file>..." to unstage)

                new file:   heritance/employee.cpp
                new file:   heritance/employee.h
                new file:   heritance/heritance.cpp
                new file:   heritance/hourlyemployee.cpp
                new file:   heritance/hourlyemployee.h
                new file:   heritance/salariedemployee.cpp
                new file:   heritance/salariedemployee.h
                new file:   stream.cpp

        3-1 commit하기. 이때 반드시 주석부분을 적어주어야한다.
        ubuntu@ip-172-31-2-64:~/gitit$ git commit -m "12-26-gitfirst"
        [master (root-commit) 755c618] 12-26-gitfirst
         Committer: Ubuntu <ubuntu@ip-172-31-2-64.ap-northeast-2.compute.internal>
        Your name and email address were configured automatically based
        on your username and hostname. Please check that they are accurate.
        You can suppress this message by setting them explicitly. Run the
        following command and follow the instructions in your editor to edit
        your configuration file:

            git config --global --edit

        After doing this, you may fix the identity used for this commit with:

            git commit --amend --reset-author

         8 files changed, 361 insertions(+)
         create mode 100644 heritance/employee.cpp
         create mode 100644 heritance/employee.h
         create mode 100644 heritance/heritance.cpp
         create mode 100644 heritance/hourlyemployee.cpp
         create mode 100644 heritance/hourlyemployee.h
         create mode 100644 heritance/salariedemployee.cpp
         create mode 100644 heritance/salariedemployee.h
         create mode 100644 stream.cpp

         4-1원격으로 저장할 장소 등록하여주기 (github을 통하여 시각적인 저장장소를 확인하기 위한 작업이다.)
        ubuntu@ip-172-31-2-64:~/gitit$ git remote add gitit https://github.com/LEEleonardo/gitfirst.git

        4-2 파일 올려질 장소 확인하기
        ubuntu@ip-172-31-2-64:~/gitit$ git remote -v
        gitit   https://github.com/LEEleonardo/gitfirst.git (fetch)
        gitit   https://github.com/LEEleonardo/gitfirst.git (push)

        4-3 파일 올려주기
        ubuntu@ip-172-31-2-64:~/gitit$ git push gitit master

        <다음과같이 홈페이지의 아이디와 페스워드를 쓰라고 나온다.>
        Username for 'https://github.com': LEEleonardo
        Password for 'https://LEEleonardo@github.com':

good!

추가

1-4.내가 git에 올려줄 파일을 생성하여주기
ubuntu@ip-172-31-2-64:~/gitit$ vi charstring.cpp

2-1 인덱스에 등록하여주기
ubuntu@ip-172-31-2-64:~/gitit$ git add charstring.cpp

2-2 인덱스 확인하기.
ubuntu@ip-172-31-2-64:~/gitit$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   charstring.cpp

3-1 commit하기. 이때 반드시 주석부분을 적어주어야한다.
ubuntu@ip-172-31-2-64:~/gitit$ git commit -m "charstring"

4-3 파일 올려주기
ubuntu@ip-172-31-2-64:~/gitit$ git push gitit master
Username for 'https://github.com': LEEleonardo
Password for 'https://LEEleonardo@github.com':

수정

1-4.내가 git에 올려줄 파일을 수정
ubuntu@ip-172-31-2-64:~/gitit$ vi stream.cpp

<상태를 확인하면 알아서 수정됨을 잡아준다.>
ubuntu@ip-172-31-2-64:~/gitit$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   stream.cpp

no changes added to commit (use "git add" and/or "git commit -a")

2-1 인덱스에 등록하여주기
ubuntu@ip-172-31-2-64:~/gitit$ git add stream.cpp

2-2 인덱스 확인하기.
ubuntu@ip-172-31-2-64:~/gitit$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   stream.cpp

3-1 commit하기. 이때 반드시 주석부분을 적어주어야한다.
ubuntu@ip-172-31-2-64:~/gitit$ git commit -m "streamfirstlinemodify"

4-3 파일 올려주기
ubuntu@ip-172-31-2-64:~/gitit$ git push gitit master
Username for 'https://github.com': LEEleonardo
Password for 'https://LEEleonardo@github.com':

확인하기

오류

! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/LEEleonardo/gitfirst.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

이러한 오류가 발생하는 경우가있다.

기존에 있는 데이터에 추가적으로 데이터를 덮어 씌울때 발생하는 에러이다.

이를 그냥 무시하기위해서는 ubuntu@ip-172-31-2-64:~/gitit$ git push gitit +master

이렇게 +를 붙여주어 무시할 수 있다.

'리눅스' 카테고리의 다른 글

MYSQL 4  (0) 2017.12.31
MYSQL2  (0) 2017.12.29
MYSQL1  (0) 2017.12.27
aws  (0) 2017.12.27
리눅스 명령어  (0) 2017.12.26
char string은 마지막이 null 값이 들어간다.
즉 n개의 글자가 char string 형태로 들어가면 n+1의 저장공간이 할당된다는 의미이다.

선언방법
char 배열을 선언과 동시에 초기화하면 c-string 이 되고 선언과 초기화를 따로하게되면 c-array 이다.

-char short[] = “abc”; 와같은 경우 자동으로 4개의 공간이 할당되는 c-string이지만 추천하지는 않는다.
-char short[] = {‘a’,b‘’,‘c’} 같은 것은 array 이다.
-char short[5]=“abcd”로 한후에 short[4]=a 이런식으로 하면 공백에 값이 들어가게 되므로 c-string--->c-array가된다.

-cstring의 각종함수
cstring으로 선안된 배열에 문자열을 넣기위해서 =처럼 대입연산자는 사용 불가능하다.
strcpy(복사할곳,복사할것); <--이런형태로 대입한다.
strcat((붙일곳,붙혀질것));
strcmp((비교1,비교2)); :동일하면 0을 리턴하고 동일하지않다면 다른값을 리턴한다.
strlength(); : 길이를 알려준다.
cout << a<<b처럼 operator overloading이 되어져 있다.
cin >> a>> b 처럼 cin으로 할때에는 cin하는 문장에서 spacebar단위로 a, b에 string이 입력된다.
만약 한줄 단위로 입력해주고 싶다면 getline을 해준다.
cin.getline(a,80) -->a라는 cstring에 80글자 내로 한줄을 입력받는다.
만약 c-string 이 아닌 그냥 string을 get line 해주고 싶다면
getline(cin,변수명) -->이렇게 해주면 된다.
굉장히 헷갈릴 것이다.

'언어 > CPP(cpp)' 카테고리의 다른 글

c++_객체지향이란?_cin_cout_cascading_우분투로 c++컴파일_flag_cout 출력소수점 정하기  (0) 2018.02.03
github_cpp  (0) 2017.12.26
static,vector(벡터)  (0) 2017.12.25
클래스 생성자  (0) 2017.12.25
sort,structure(구조체)  (0) 2017.12.25

static

폰을 끄더라도 dram,sram으로 인하여.. static메모리가 존재하여 데이터를 유지한다.

static메모리는 파워가 없어도 데이터를 유지한다.

static variable 자기가 정의된 함수밖에서도 메모리가 유지된다. 일반적인 변수나 함수는 함수 안에서만 유지가 된다.

static function

프로그램이 loading할 때 global 공간에서 생성이되고 실행중에는 만들어지지 않는다

static int nA=3; 을하면 global공간에 만들어지고 앞이 sheild가 쳐져서 보이지 않게된다.

#include "stdafx.h"

#include

using namespace std;

void ShowStaticVariableExample();

int main()

{

ShowStaticVariableExample();

ShowStaticVariableExample();

return 0;

}

//nA는 사용할때마다 죽어서 초기화되면 살아있던게 죽고 다시생김

void ShowStaticVariableExample()

{

static int nA = 3;

nA = nA + 1;

cout << nA << endl;

}

static member variable program loading 할 때 공간이 잡힌다. 즉 객체 생성시에는 더 이상 공간이 잡히지 않는다.

매개변수로 포인터를 받고, 이를 배열에 넣기 위해서는 바로는 방법이없다.

이유는 포인터=배열이름을 통하여 포인터의 정의는 가능하지만

배열이름=포인터를 통하여 배열이름으로 다른 포인터로 재정의는 불가능하다.

따라서 set함수를 통하여 배열[]=포인터[] 꼴로 해준다.

CTheater::CTheater(string strName, int nTriptime, int* pnShowtime)

{

m_strName = strName;
m_nTripTime = nTriptime;
SetShowTime(pnShowtime, 10);

} static을 이러한 방식으로 사용한다면 오류가 뜬다.

즉 CTheater가 static변수를 사용하기 위해서는 .cpp나 함수위에
int CTheater::m_nTheater = 0;
이것을 위에 써준다. CTheater 이라는 클래스의 static변수를 0으로 초기화 한다는 의미이다.
그냥 static 변수를 함수에서 사용하기 위해서는 함수 위에 static 메모리를 미리 선언 및 초기화를 해준다고 생각하자.
함수를 사용할 때에는 헤더파일에서 맨앞에 static을 붙여주고 이를 정의하는 부분은 그냥 쓴다. 그리고 사용할 때 클래스명::함수명() 이렇게 사용하여 함수가 클래스변수에 포함되는 것이 아닌 그냥 사용 가능하도록 한다.
그것이 static의 방식이다. 어차피 static은 포함되는 것이 아니라 그냥 사용한다 하더라도 그값이 유지가 되어 버리기 때문에 동일하게 된다.

vector

array는 한번정한 크기를 바꿀 수 없다.

vector는 크기를 가변적으로 바꿀 수 있다.

array는

int pA[10]; int *pnA; pnA=new int[10];

vector는 크기가 가변적인다.

array가 커지기도 하고 작아지기도 한다.

vecter 변수명; //int 형의 벡터가 나온다.

데이터를 넣을 때에는 v.push_back이라는 함수를 넣는다. 최초로 넣을때에는 push back을 한다.

벡터는 stl-templet 형태의 library 이다.

templet

하나의 틀을 만들어 두고 그틀로 클래스를 만든다.

각각의 type를 넣으면 컴파일러가 그 type을 넣어 코딩을 해준다.

int vertor, double vector을 만드는데 templet을 만들면 int를 쓰면 컴파일러가 자동 generation 해준다.

'언어 > CPP(cpp)' 카테고리의 다른 글

github_cpp  (0) 2017.12.26
char string  (0) 2017.12.25
클래스 생성자  (0) 2017.12.25
sort,structure(구조체)  (0) 2017.12.25
array(배열)  (0) 2017.12.25

생성과 용례

'언어 > CPP(cpp)' 카테고리의 다른 글

char string  (0) 2017.12.25
static,vector(벡터)  (0) 2017.12.25
sort,structure(구조체)  (0) 2017.12.25
array(배열)  (0) 2017.12.25
영화 별점 표본 검사 코드  (0) 2017.12.25

sort algorithm

1)selection sort 뽑을 때 작은수나 큰수부터 차례대로 뽑음

2)insertion sort 넣을 때 작은수나 큰수부터 차례대로 넣음

ex)원하는 숫자를 넣으면 알아서 순서를 배열해주는 알고리즘

{.cpp}
// ConsoleApplication27.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

const int declared_size = 20;

void fillarray(int a[], int size, int& numberused);

int indexofsmallest(int a[], int startindex, int numberused);

void sort(int a[], int numberused);

void swapvalues(int& v1, int& v2);

int search(int a[], int numberused, int target);

int main()
{
    cout << "this program sort\n";
    int samplearray[10], numberused;
    fillarray(samplearray, 10, numberused);
    sort(samplearray, numberused);
    cout << "it is \n";
    for (int index = 0; index < numberused; index++)
    {
        cout << samplearray[index] << "";
        cout << endl;
    }


    return 0;


}

void fillarray(int a[], int size, int& numberused)
{
    cout << "enter" << size << " no negative nube\n mark the endof lis is negative ";
    int next, index = 0;
    cin >> next;
    while ((next > 0) && (index < size))
    {
        a[index] = next;
        index++;
        cin >> next;
    }
    numberused = index;
    cout << "index is"<<index << endl;
}

void sort(int a[], int numberused)
{
    int indexofnextsmallest;
    //맨마지막에 두개가 남을때 이것을 한번만 돌리면된다. 이유는 둘중작은거 하나만 찾으면 되기 때문이다.
    for (int index = 0; index < numberused - 1; index++)
    {
        indexofnextsmallest = indexofsmallest(a, index, numberused);
        swapvalues(a[index], a[indexofnextsmallest]);
    }
}

void swapvalues(int&v1, int& v2)
{
    int temp;
    temp = v1;
    v1 = v2;
    v2 = temp;
}

int indexofsmallest(int a[], int startindex,int numberused)
{
    //min값에 a의 시작값을 넣어준다.
    int min = a[startindex];
    //indexofmin에는 index의 시작값을 넣어준다.
    int indexofmin = startindex;
    //a의 index는 startindex+1부터 시작된다.
    //만약 a[index]가 a의 맨시작점인 min값보다 작다면 min값에 작은값a을 넣어준다.
    //indexofmin에는 작은값을 갖는 index값을 넣어준다.
    for (int index=startindex+1;index < numberused; index++)
        if (a[index] < min)
        {
            min = a[index];
            indexofmin = index;
        }
    return indexofmin;
}

//a배열과 그것에대한 크기와 taget값을 받아준다.
//target과 동일한 a[]배열의 index값을 찾아준다.
int search(int a[], int numberused, int target)
{
    int index = 0;
    bool found = false;
    //a[index]값=target과 동일한 값이되면 루프를 멈춘다.
    while ((!found) && (index < numberused))
    {
        if (target == a[index])
            found = true;
        else
            index++;
    }
    if (found)
        return index;
    //else가 나오는 경우는 a[]의 배열이 끝나도록 target과 동일한 값이 없을때 이다.
    else
        return -1;
}

structure part

구조체이다.

C/C++ 언어는 기본 데이터형을 최소화하기 위해서 많이 사용하는 형식의 데이터형만을 기본 데이터형 으로 정의하고 나머지는 프로그래머가 데이터형을 정의해서 사용할수 있도록 만들어졌는데 이를 구조체를 통해 정의한다.

structure안에 정의된 변수를 membervaluable이라 한다.

membervaluable 의 순서는 중요하지 않다.

선언방법 struct <구조체명> { membervaluable 선언; };

예제)

{.cpp}
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct Theater
{
    string strName;
    int nTripTime;
    int pShowTime[10];
};

int main()
{
    Theater aTheater;
    aTheater = { "Lotte Cinema in Gunkuk Univ station",10,{9,10,11,13,14,15,16,18,20,23} };
    cout<<aTheater.strName<<endl<<"The time from home to the cinema : "<< aTheater.nTripTime << "minutes"<<endl<<"Movie : kings man2";
    for (int i=0; i < 10; i++)
    {
        cout << endl << i+1 << "- showing time : " << aTheater.pShowTime[i]<<":00";
    }


    return 0;
}

'언어 > CPP(cpp)' 카테고리의 다른 글

static,vector(벡터)  (0) 2017.12.25
클래스 생성자  (0) 2017.12.25
array(배열)  (0) 2017.12.25
영화 별점 표본 검사 코드  (0) 2017.12.25
assert,debug,driver,stub,중단점,디버그,조사식  (0) 2017.12.25

설명

영화 별점을 메기는 사람마다 quality level을 결정하고 평균 값을 score로 사용한다.

알고리즘은 사람의 신뢰도가 수렴할때까지 수행된다.

신뢰도에대한 알고리즘의 수식은 다음과 같다.

rating score는 다음과 같다.

코드

{.cpp}
// ConsoleApplication24.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include<string.h>
#include<cmath>
using namespace std;

//main함수로부터의 도표를 읽어들여 값을 대입해주는 함수 readChart.
void readChart(int** pDataset, int voter, int election)
{
    //초기화된 배열에 원하는값을 넣어준다.
    for (int i = 0; i < election; i++)
    {
        for (int j = 0; j < voter; j++)
        {
            cin >> pDataset[i][j];

            //chart[i] = new int[voter];
            //memset(chart[i], 0, 4 * voter);
        }
    }

}

//정답만 바로 궁금하다면 사용해줄 함수 readmacro.
void readmacro(int** pDataset)
{
    //초기화된 배열에 원하는값을 넣어준다.
    pDataset[0][0] = 1;
    pDataset[0][1] = 1;
    pDataset[0][2] = 1;
    pDataset[0][3] = 2;
    pDataset[0][4] = 2;
    pDataset[1][0] = 1;
    pDataset[1][1] = 2;
    pDataset[1][2] = 2;
    pDataset[1][3] = 3;
    pDataset[1][4] = 2;
    pDataset[2][0] = 3;
    pDataset[2][1] = 4;
    pDataset[2][2] = 4;
    pDataset[2][3] = 4;
    pDataset[2][4] = 2;
    pDataset[3][0] = 1;
    pDataset[3][1] = 3;
    pDataset[3][2] = 3;
    pDataset[3][3] = 3;
    pDataset[3][4] = 1;
    pDataset[4][0] = 2;
    pDataset[4][1] = 2;
    pDataset[4][2] = 2;
    pDataset[4][3] = 1;
    pDataset[4][4] = 1;
    pDataset[5][0] = 1;
    pDataset[5][1] = 2;
    pDataset[5][2] = 2;
    pDataset[5][3] = 1;
    pDataset[5][4] = 1;
}

//*T를 초기화하는 함수를 통하여 초기화. 일단 모든사람의 신뢰값으로 1을 준다.
void firstinitial(double* T, int voter)
{
    for (int i = 0; i < voter; i++)
        T[i] = 1;
}
//식2를 구현하는 함수 만들기
void modify2(double **rho, int** pDataset, int election, int item, int voter)
{
    //해당작품의 해당점수를 선택한 사람들의 신뢰도의 합 구하기
    //voter의값을 이용하기 위해 voter2 정의
    int voter2 = voter;
    for (int a = 0; a < election; a++)
    {
        //여기서부터 rho의 j열 i행에 어떠한 수가 들어갈지를 계산하여 준다.즉 식 (2)의 구현을 나타낸다.
        //일단 식 2에서 분모의 계산을 해보겠다.
        //1점을 고른 사람들의 신뢰도의 합을 c[1],2점을 고른 사람들의 신뢰도합을 c[2]...이런식으로 알고리즘을 구성하겠다.
        //점수n의 사람에대한 신뢰도의합 c[n]으로 나타냄.
        int squresum = 0;
        double squreroot = 0;
        int c[5];
        c[0] = 0; c[1] = 0; c[2] = 0; c[3] = 0; c[4] = 0;
        for (int l = 0; l < voter; l++)
        {

            for (int m = 0; m < 5; m++)
            {
                if (pDataset[a][l] == m + 1)
                    c[m] = c[m] + 1;
            }

        }
        //제곱의 합을 더한후에 루트를 씌운다.
        for (int n = 0; n < item; n++)
            squresum = squresum + c[n] * c[n];
        squreroot = sqrt(squresum);
        for (int o = 0; o < item; o++)
        {
            rho[o][a] = c[o] / squreroot;
        }
    }
    cout << endl << "<2nd answer>" << endl;
    for (int a = 0; a < item; a++)
    {
        for (int j = 0; j < election; j++)
        {
            //소수점 두자리까지만 출력하여 간편히 보기위하여 다음과같은 설정을 만족하자.
            cout.setf(ios::fixed);
            cout.setf(ios::showpoint);
            cout.precision(2);
            cout << rho[a][j] << "\t";
            //chart[i] = new int[voter];
            //memset(chart[i], 0, 4 * voter);
        }
        cout << endl;
    }
}

int main()
{
    cout << "<Iterative Method for Calculating Robust Rating Scores>\n*press keybord <anything+enter> ->answer of work.\n*press keybord <0+enter> ->change election and voter\n";
    long double epsil;
    long double ee;
    int voter = 5;
    int election = 6;
    int sel;
    cin >> sel;
    int item = 5;
    //동적할당 방식을 이용.new int[n] n숫자만큼의 배열을 할당시켜줌.
    //pDataset 라는 포인터로 이중배열을 가리킴

    int** pDataset = new int*[election];
    //메모리 공간을 memset이라는 함수를 이용하여초기화
    //루프를 지날수록 차트의행이 증가
    for (int i = 0; i < election; i++)
    {
        pDataset[i] = new int[voter];
        memset(pDataset[i], 0, 4 * voter);
    }
    //readchart에 voter와 election값을 같이 달아주는 이유는 도표를 읽는함수를 main함수로 return하기 위해서이다.(이차원은 길이가 동일해야한다.)

    readmacro(pDataset);

    if (sel == 0)
    {
        cout << "<number of voter>" << endl;
        cin >> voter;

        cout << "<number of election>" << endl;
        cin >> election;
        cout << "<item for election>" << endl;
        readChart(pDataset, voter, election);
    }
    cout << endl << "<1st answer>" << endl;
    for (int i = 0; i < election; i++)
    {
        for (int j = 0; j < voter; j++)
        {
            cout << pDataset[i][j] << "\t";
            if (pDataset[i][j] > 5)
            {
                cout << endl << "You can have score maximum 5!!!";
                return 0;
            }
            //chart[i] = new int[voter];
            //memset(chart[i], 0, 4 * voter);
        }
        cout << endl;
    }

    double* T = new double[voter];
    //*T를 초기화하는 함수를 통하여 초기화
    firstinitial(T, voter);
    //2차원 로우li를 담는 함수 rho 선언및  초기화
    double** rho = new double*[item];
    for (int i = 0; i < item; i++)
    {
        rho[i] = new double[election];
        memset(rho[i], 0, 8 * election);
    }
    double** rho2 = new double*[item];
    for (int i = 0; i < item; i++)
    {
        rho2[i] = new double[election];
        memset(rho[i], 0, 8 * election);
    }

    //수식2를 계산하는 함수에 rho를 대입
    modify2(rho, pDataset, election, item, voter);
    epsil = 0;
    ee = 0;
    long double epsil2;

    cout << endl;
    ///////////////////////////////////////////////////////////////////////////////

    for (int p = 0; p < 20; p++)
    {

        for (int i = 0; i < voter; i++)
        {
            T[i] = 0;
        }
        //main함수에서 수식 3번함수 구현하기.
        for (int i = 0; i < voter; i++)
        {
            for (int j = 0; j < election; j++)
            {
                //작품에 대하여 voter가 선택한 점수를 selectitem으로 선언
                int selectitem = pDataset[j][i] - 1;
                //T[i]에는 작품에 해당하는 점수의 신뢰도의 합이 들어있다.
                T[i] = T[i] + rho[selectitem][j];
            }
        }
        for (int a = 0; a < election; a++)
        {
            //여기서부터 rho의 j열 i행에 어떠한 수가 들어갈지를 계산하여 준다.즉 식 (2)의 구현을 나타낸다.
            //일단 식 2에서 분모의 계산을 해보겠다.
            //1점을 고른 사람들의 신뢰도의 합의제곱을 c[0],2점을 고른 사람들의 신뢰도합을 c[1]...이런식으로 알고리즘을 구성하겠다.
            //점수n의 사람에대한 신뢰도의합 c[n]으로 나타냄. 즉 4번식의 분자에서 제곱안에 있는수를 의미한다.
            double squresum = 0;
            double squreroot = 0;
            int c[5];
            c[0] = 0; c[1] = 0; c[2] = 0; c[3] = 0; c[4] = 0;
            //a가 작품,l은 사람, m 은 점수를 의미한다.
            for (int l = 0; l < voter; l++)
            {

                for (int m = 0; m < 5; m++)
                {
                    //a번째 작품에서 l번째 사람의 점수가 내가 구하고자하는점수일때 그사람의 신뢰도의 제곱을 c[m]에 제곱하여 더해준다.
                    if (pDataset[a][l] == m + 1)
                        c[m] = c[m] + T[l] * T[l];
                }

            }
            //제곱의 합을 더한후에 루트를 씌운다.
            for (int n = 0; n < item; n++)
            {
                squresum = squresum + c[n] * c[n];
            }
            squreroot = sqrt(squresum);

            for (int o = 0; o < item; o++)
            {
                rho2[o][a] = c[o] / squreroot;
            }
        }

        //입실론값을 구하기위하여 차의 제곱의 합의 루트을 구해준다.
        epsil2 = epsil;
        for (int a = 0; a < item; a++)
        {
            for (int j = 0; j < election; j++)
            {
                ee = rho2[a][j] - rho[a][j];
                ee = ee*ee;
                epsil = epsil + ee;
            }
        }
        epsil = sqrt(epsil);

        for (int a = 0; a < item; a++)
        {
            for (int j = 0; j < election; j++)
            {
                rho[a][j] = rho2[a][j];
            }

        }
        //epsil - epsil2를 해준 이유는 epsil의 값에 대한 0의 초기화가 함수 4에대한 loop밖에 있으므로 그때그때 빼주어야한다.
        if (epsil - epsil2 < 0.0001)
        {
            cout << endl << "<3rd answer>" << endl;
            for (int a = 0; a < item; a++)
            {
                for (int j = 0; j < election; j++)
                {
                    //소수점 두자리까지만 출력하여 간편히 보기위하여 다음과같은 설정을 만족하자.
                    cout << rho[a][j] << "\t";
                    //chart[i] = new int[voter];
                    //memset(chart[i], 0, 4 * voter);
                }
                cout << endl;
            }
            cout.precision(10);
            cout << endl << "epsilon : " << epsil - epsil2 << endl << "counted loop:" << p;
            break;
        }

    }//chart[i] = new int[voter];
     //memset(chart[i], 0, 4 * voter);
     //listpi 함수를 정의하겠다.

    double* listpi = new double[election];

    for (int l = 0; l < election; l++)
    {
        double denom = 0;        //분모값을 denom으로 선언
        double numer = 0;
        listpi[l] = 0;
        //분모
        for (int i = 0; i < 5; i++)
        {//squreroot변수*변수 가 변수^1.5임을 이용

            double result1 = sqrt(rho[i][l])*rho[i][l];
            denom = denom + result1;

        }
        //분자
        for (int i = 0; i < 5; i++)
        {
            double result2 = sqrt(rho[i][l])*rho[i][l] * (i + 1);
            numer = numer + result2;
        }
        listpi[l] = numer / denom;

    }
    cout << endl << endl << "<4th answer>\n";
    cout.precision(5);
    for (int i = 0; i < election; i++)
    {
        cout << "Rating score " << i + 1 << " election is:" << listpi[i] << endl;
    }
}

결과

assert

용도: 프로그램 실행시 해당하는 조건이 참이면 그대로 프로그램을 실행하고 해당하는 조건이 거짓이면 프로그램을 중단시킨다. 이를통해 있어서는 안되는 조건의 사용을 막아준다.

사용방법:

#include ---> 로 library 호출

assert(조건)-->조건이 참이여야만 나머지 코드를 실행

ex)조건은 b가 0 이 아니여야하지만 0을 넣었을 때 어떠한 결과가 나오는지 살펴보았다

{.cpp}
#include "stdafx.h"

#include <cassert>

#include <iostream>

using namespace std;

int main()

{

int a = 1, b = 0;

int result;

assert(b != 0);

result = a + b;

cout << result;

return 0;

}

driver & stub

driver:모듈을 데스트하기 위하여 사용한다.

구성: 입력,실행,출력으로 되어있다.

ex)unitPirce라는 함수의 기능을 알기위하여 driver를 통하여 알아보기

{.cpp}
#include "stdafx.h"

#include <cassert>

#include <iostream>

using namespace std;


double unitPrice(int diameter, double price)

{

const double PI = 3.14;

double radius, area;

radius = diameter / static_cast<double>(2);

area = PI*radius*radius;

return (price / area);

}

int main()

{

double diameter, price;

char ans;


cout << "PUT VALUE TO DIAMTER AND PRCIE:" << endl;

cin >> diameter >> price;--->입력을 해준다,

cout << "unitprice value :" << unitPrice(diameter, price) << endl;-->실행 및 출력을 한다.




return 0;

}

디버거: visual studio 는 컴파일러뿐 아니라 디버거가 있다. 디버거는 프로그램의 속을 들여다 볼 수 있다.

stub은 디버거와 함께 이용된다.

사용방법은 다음과같다.

일단 내가 실행되는 과정을 보고싶은 코드에 F9을 눌러 중단점을 지정해준다

그리고 F10을 눌러가며 그다음단계를 확인할 수 있다.

오류문구:“현재 코드 페이지(949)에서 표시할 수 없는 문자가 파일에 들어 있습니다. 데이터가 손실되지 않게 하려면 해당 파일을 유니코드 형식으로 저장하십시오.”

문제점:한글인식이 되지않아 코드를 제대로 인식하지못함.

1.다른이름으로 저장하기를 눌러준다.

2.저장(s)의 우측 화살표를 눌러준다.

3.인코딩하여 저장한다.(무슨 다른이름으로 저장하시겠습니까?? 뜨면 그냥 예 한다.)

4.한국어(완성)-코드 페이지 20949로 지정한다.

5.확인후 컴파일한다.

visual strudio 2016의 문제점을 찾아 해결

맨처음시작시

“현재 코드 페이지(949)에서 표시할 수 없는 문자가 파일에 들어있습니다. 데이터가 손실되지 않게 하려면 해당파일을 유니코드 형식으로 저장하십시오.”

라는 오류 문구가 뜬다.

-문제점: 미리 컴파일된 헤더가 사용중임

-해결

프로젝트-consoleapplication속성-c/c++-미리컴파일된 헤더-미리컴파일된 헤더 사용안함 설정

+ Recent posts