반응형

7.9> 통계를 내는 Statistics 클래스를 만들려고 한다. 데이터는 Statistics 클래스 내부에 int 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 Statistics 클래스와 !, >>, <<, ~ 연산자 함수를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class Statistics{

private:

        int size; //동적 배열의 사이즈

        int index; //마지막 원소의 인덱스

        int *p; //동적 배열을 가리킬 포인터

public:

        Statistics(int size=5,int index=-1); //기본 사이즈 5, 인덱스 -1(nothing)

        friend bool operator!(Statistics op);

        void operator>>(int &op);

        Statistics& operator<<(int op);

        void operator~();

       

};

Statistics::Statistics(int size,int index){

        this->size=size;

        this->index=index;

        p=new int[size]; //size 크기만큼의 int 동적 배열 할당

}

 

bool operator!(Statistics op){

        if(op.index==-1) //index -1이면 true 반환

               return true;

        else

               return false;

}

void Statistics::operator>>(int &op){ //평균구하는 함수

        int sum=0;

        for(int i=0;i<index+1;i++){sum+=p[i];} //실제 원소 개수는 index+1 (0부터시작하니까)

        op= sum/(index+1); //op 평균값 넣어줌(참조라서 원본 바뀜)

}

Statistics& Statistics::operator<<(int op){

        index++; //인덱스 증가

        if(size<=index){ //인덱스를 하나키웠는데 size 크기 같으면 배열 크기보다 원소가 많은 경우

               int *tmp=new int[size+5]; //하나씩 키우면 자주 없앴다 만들었다 해야하니 5개씩 늘린다.

               for(int i=0;i<size;i++){ //(size+5 하면 p크기가 size라서 오류날 있음)

                       tmp[i]=p[i]; //p 원소를 전부 tmp 복사

               }

               delete []p; //p 가리키는 동적배열 힙에 반환

               p=tmp; //tmp 가리키는 배열을 p 가리키게 (어차피 tmp 사라지므로 깊은 복사 필요 없음)

               size+=5; //size 5 추가

        }

        p[index]=op; //index 오퍼랜드 대입

        return *this; //현재 객체의 참조 리턴(이름)

}

void Statistics::operator~(){ //전부 출력하는 함수

        for(int i=0;i<index+1;i++){ //원소 개수 = index+1

               cout<<p[i]<<" ";

        }

        cout<<endl;

}

 

int main(void){

        Statistics stat;

        if(!stat) cout<<"현재 통계 데이타가 없습니다."<<endl;

        int x[5];

        cout <<"5 개의 정수를 입력하라>>";

        for(int i=0;i<5;i++) cin >> x[i]; //x[i] 정수 입력

        for(int i=0;i<5;i++) stat << x[i]; //x[i] 값을 통계 객체에 삽입한다.

        stat << 100 << 200; //100, 200 통계 객체에 삽입한다.

        ~stat; //통계 데이타를 모두 출력한다.

 

        int avg;

        stat>>avg; //통계 객체로부터 평균을 받는다.

        cout<<"avg="<<avg<<endl; //평균을 출력한다.

        return 0;

}

 

<결과창>

               

                    


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
반응형

6.6> 동일한 크기의 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility2 클래스를 만들고 이 클래스를 이용하여 아래 결과와 같이 출력하도록 프로그램을 완성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility2{

public:

        static int* concat(int s1[], int s2[], int size);

        //s1 s2 연결한 새로운 배열을 동적 생성하고 포인터 리턴

        static int* remove(int s1[], int s2[], int size, int& retSize);

        //s1에서 s2 있는 숫자를 모두 삭제한 새로운 배열을 동적 생성하여 리턴, 리턴하는

        //배열의 크기는 retSize 전달. retSize 0 경우 NULL 리턴

};

int* ArrayUtility2::concat(int s1[], int s2[], int size){

        int *p=new int[size*2]; //동일한 크기의 배열이므로 size *2 배열을 동적 생성

        for(int i=0;i<size;i++){

               p[i]=s1[i]; //0~4 인덱스는 s1 초기화

               p[i+size]=s2[i]; //5~9 인덱스는 s2 초기화

        }

        return p; //동적배열을 가리키는 주소 리턴

}

int* ArrayUtility2::remove(int s1[], int s2[], int size, int& retSize){

        int i; int j; int count=0; //빼기 배열 만들 사용할 카운터

        for(i=0;i<size;i++){

               for(j=0;j<size;j++){

                       if(s1[i]==s2[j]){

                              s1[i]=NULL; //s2 원소를 s1 일일이 비교하여 같으면 NULL 교체

                              break; //어차피 1번겹치든 2번겹치든 빼는 것은 한번이기 때문에 break 가능

                       }

               }

        }

        for(i=0;i<size;i++){

               if(s1[i]!=NULL)

                       retSize++; //원소값이 NULL 아니면 retSize 증가

        }

        if(retSize==0) return NULL; //retSize 0이면 NULL포인터 리턴

        int *p=new int[retSize]; //retSize 크기의 인트형 배열 동적 할당

        for(i=0;i<size;i++){

               if(s1[i]!=NULL){ //s1[i] NULL 아니면

                       p[count]=s1[i]; //p[count] 대입

                       count++;

               }

        }

        return p; //동적배열을 가리키는 주소 리턴

}

int main(void){

        int x[5];

        int y[5];

        int i;

        int *conc; //합친 배열 주소 받음

        int *del; // 배열 주소 받음

        int size=sizeof(x)/sizeof(x[0]); //(4*5)/4=5

        int retSize=0; //초기화 안하고 참조에 쓰면 오류생김

        cout<<"정수를 5 입력하라. 배열 x 삽입한다>>";

        for(i=0;i<5;i++){cin>>x[i];} //배열 입력

        cout<<"정수를 5 입력하라. 배열 y 삽입한다>>";

        for(i=0;i<5;i++){cin>>y[i];}

        conc=ArrayUtility2::concat(x,y,size); //합친 배열

        for(i=0;i<size*2;i++){cout<<conc[i]<<" ";} //출력

        cout<<endl;

        del=ArrayUtility2::remove(x,y,size,retSize); // 배열

        cout<<"배열 x[]에서 y[] 결과를 출력한다. 개수는 "<<retSize <<endl;

        for(i=0;i<retSize;i++){cout<<del[i]<<" ";} //출력

        cout<<endl;

        return 0;

}

 

<결과창>




반응형
반응형

6.5> 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility{

public:

        static void intToDouble(int source[], double dest[], int size);

        //int[] double[] 변환

        static void doubleToInt(double source[], int dest[], int size);

        //double[] int[] 변환

};

void ArrayUtility::intToDouble(int source[], double dest[], int size){

        for(int i=0;i<size;i++){

               dest[i]=(double)source[i]; //강제 형변환

        }

}

void ArrayUtility::doubleToInt(double source[], int dest[], int size){

        for(int i=0;i<size;i++){

               dest[i]=(int)source[i]; //강제 형변환, 소수점은 날아간다.

        }

}

int main(void){

        int x[]={1,2,3,4,5};

        double y[5];

        double z[]={9.9,8.8,7.7,6.6,5.6};

 

        ArrayUtility::intToDouble(x,y,5); // x[]-> y[]

        for(int i=0;i<5;i++) cout << y[i] << ' ';

        cout << endl;

        ArrayUtility::doubleToInt(z,x,5); //z[]->x[]

        for(int i=0;i<5;i++) cout << x[i] << ' ';

        cout << endl;

        return 0;

}


<결과창>



}


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
using namespace std;
 
int main(void){
 
    int a[2]={6,10};
    int *p=a; //포인터 p는 배열a의 첫번째 원소를 가리키는 포인터
    int &r=*a; //r은 a의 첫번째 원소의 참조
    int &r2=r; //r2는 r의 참조 (참조의 참조)
 
    cout<<a[0]<<endl//6
    cout<<*p<<endl//6
    cout<<r<<endl//6
    cout<<r+1<<endl//6+1=7
    cout<<a<<endl//주소
    cout<<&r<<endl//첫번째 원소의 주소 =a
    cout<<*(&r)<<endl//레퍼런스 주소의 역참조 = 6
    cout<<*(&r+1)<<endl//레퍼런스 주소에 1을 더한것의 역참조 = 10(2번째 원소)
    cout<<r2<<endl//r2는 r을 가리키므로 6
}
cs


포인터는 주소가 담기는 메모리가 할당 된다.

레퍼런스는 메모리 상의 특정 공간을 차지하는 것이 아니라 컴파일 시에

원래 레퍼런스가 참조하던 변수의 *(주소값)으로 대체되는 것이다.







반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
반응형

인하대학교 전자공학과 데이터 구조 포인터, 어레이 과제 (pointer, array)


인하대학교 전자공학과 데이터 구조 하노이의 탑, 이진 탐색(binary search, tir, recursive)


인하대학교 전자공학과 데이터 구조 시스템 스택, 선형 리스트 (system stack, linear list)


인하대학교 전자공학과 데이터 구조 preorder, postorder, max heap


인하대학교 전자공학과 데이터 구조 dfs, bfs, 프림, 크루스칼 (prim, kruskal)


소스코드, 수도코드, 플로우차트(순서도), 분석 및 고찰, 결과창 등이 들어있는 보고서입니다.


전부 만점받은 보고서입니다. 

반응형
반응형

1. Array : Let’s assume that we have the following declaration:

1.1. Please store the above data using scanf() function in two 2-dimension array, respectively. You can show the result.

 

1.2. Please create a new array ‘element[2][3]’ to obtain the sum of the value of First array and Second array. For example,

element[1][2] = First[1][2]+Second[1][2].

element[2][1] = First[2][1]+Second[2][1].




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
    {{16,18,23},{54,91,11}}          {{24,52,77},{16,19,59}}
    1-1)Please store the above data using  function in two  2-dimension array, respectively. You can show the result.
    1-2)Please create a new array ‘Element[2][3]’ to obtain the sum of the value of First array and Second array. For example,
        Element[1][2] = First[1][2]+Second[1][2]. 
        Element[2][1] = First[2][1]+Second[2][1].
    ROW : 행 수 COL : 열 수
    array_input : 배열에 원소 값을 사용자가 입력할 수 있게 하는 함수
    array_print : 배열을 원소별로 출력해주는 함수
    array_sum   : 배열의 합을 구해주는 함수
    First[ROW][COL] : 2*3 사이즈의 2차원 배열1
    Second[ROW][COL] : 2*3 사이즈의 2차원 배열2
    Element[ROW][COL] : 2*3 사이즈의 2차원 배열, 동일한 위치의 First와 Second 의 원소의 합이 들어갈 배열
*/
#include <stdio.h>
#define ROW 2
#define COL 3
void array_input(int num,int array[][COL]);
void array_print(int num,int array[][COL]);
void array_sum(int array1[][COL],int array2[][COL],int array3[][COL]);
int main(void)
{
    int First[ROW][COL];
    int Second[ROW][COL];
    int Element[ROW][COL];
    array_input(1,First);
    array_input(2,Second);
    array_sum(First,Second,Element);
    printf("\n");
    array_print(1,First);
    printf("\n");
    array_print(2,Second);
    printf("\n");
    array_print(3,Element);
    return 0;
}
void array_input(int num,int array[][COL])
{
    int i;int j;
    printf("<%d번째 배열 입력>\n",num);
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        printf("%d번배열[%d][%d] 값 입력 : ",num,i,j);
        scanf("%d",&array[i][j]);
        }
    }
}
void array_print(int num,int array[][COL])
{
    int i;int j;
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        printf("%d번배열[%d][%d] : %d\n",num,i,j,array[i][j]);
        }
    }
}
void array_sum(int array1[][COL],int array2[][COL],int array3[][COL])
{
    int i;int j;
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        array3[i][j]=array1[i][j]+array2[i][j];
        }
    }
}
cs

 

 


2. Pointer : Let’s assume the next arrangement was declared. Calculate the final value of the following expression:

2.1. *(**p+3), *(**p+1), p[0], **(p[1]+1), *(p[1] +1)

2.2. *text, *(text+3), *(text+7)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
int main(void)
{
    char *p[3][2]={"abcd","efgh","ijklm","nop","qrstuv","wxyz"};
    char *text;
    char more[]="Happy Holidays";
    text=&more[4]; //'y'의 주소
    printf("*(**p+3)=%c\n",*(**p+3));
    printf("*(**p+1)=%c\n",*(**p+1));
    printf("p[0]=%x\n",p[0]);
    printf("**(p[1]+1)=%c\n",**(p[1]+1));
    printf("*(p[1]+1)=%x\n",*(p[1]+1));
    printf("\n");
    printf("*text=%c\n",*text);
    printf("*(text+3)=%c\n",*(text+3));
    printf("*(text+7)=%c\n",*(text+7));
}
cs







반응형
반응형

4.4 다음 두 개의 static 메소드를 가진 ArrayUtility2 클래스를 만들어보자. ArrayUtility2 클래스를 이용하는 테스트용 프로그램도 함께 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package HW1_JAVA;
class ArrayUtility2{//s1과 s2를 연결한 새로운 배열 리턴
    static int[] concat(int s1[], int s2[]){ //int형배열을 리턴으로하는 메소드 concat(인자 int형배열 2개)
        int conc[]=new int[s1.length+s2.length]; //s1과 s2 길이를 더한 길이를 갖는 인트형 배열 conc
        int i; //int 형 변수 i 선언
        for(i=0;i<conc.length;i++//i=0부터 conc의 길이보다 작을 때까지 반복
        {
            if(i<=4//i가  4 이하이면 conc[i]에 s1[i] 대입
            conc[i]=s1[i];
            else    //i가 5이상이면 conc[i]에 s2[i-5] 대입
            conc[i]=s2[i-5];
        }
        return conc;}  //conc 배열 리턴
    static int[] remove(int s1[], int s2[]){ //s1에서 s2 배열의 숫자를 모두 삭제한 새로운 배열 리턴
        int i; int j; //인트형 변수 i,j 선언
        int s3[]=new int[s1.length]; //s1.length의 길이를 갖는 배열 s3 선언
        LABEL : for(i=0;i<s1.length;i++//i는 0부터 s1.length 미만까지 반복
        {
            for(j=0;j<s2.length;j++//j는 0부터 s2.length 미만까지 반복
            {
                if(s1[i]==s2[j])  //s1[i]와 s2[j]가 같으면 루프 중단 후 LABEL로 점프(증가식은 진행됨)
                    continue LABEL;
            }
            s3[i]=s1[i]; //s3[i]에 s1[i] 대입
        }
        return s3;} } //배열 s3 리턴
public class ArrUse {
    public static void main(String[] args) {
        ArrayUtility2 ut=new ArrayUtility2(); //ArrayUtility2 class의 객체와 레퍼런스 변수 선언
        int a[]={1,2,3,4,5}; //int형 배열 a 선언 및 초기화
        int b[]={3,4,5,6,7}; //int형 배열 b 선언 및 초기화
        int c[]=new int[a.length+b.length]; //int형 배열 c 선언
        int d[]=new int[a.length]; //int형 배열 d 선언
        int i; //int형 변수 i 선언
        c=ut.concat(a, b); //배열 c에 concat 메소드의 리턴값 대입
        d=ut.remove(a, b); //배열 d에 remove 메소드의 리턴값 대입
        for(i=0;i<c.length;i++//i=0부터 c.length 미만까지 반복
        {
            System.out.print(c[i]+" "); //c[i]와 띄어쓰기 출력
        }
        System.out.println(); // 개행문자 출력
        for(i=0;i<d.length;i++//i=0부터 d.length 미만까지
        {
            if(d[i]!=0//int형 배열은 0으로 자동초기화 되기 때문에 출력안하려면 논리판별
            System.out.print(d[i]+" "); //d[i]와 띄어쓰기 출력
        }}}
 
cs






반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

추상 클래스  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
반응형

3.11>배열과 반복문을 이용하여 프로그램을 작성해보자. 키보드에서 정수로 된 돈의 액수를 입력 받아 오만 원권, 만 원권, 천 원권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전이 각 몇 개로 변환되는지 출력하라. 예를 들어 65370이 입력되면 오만 원권 1, 만 원권 1, 천 원권 5, 100원짜리 동전 3, 50원짜리 동전 1, 10짜리 동전 2개이다. 이때 반드시 다음의 배열을 이용하고 반복문으로 작성하라.


int []unit={50000,10000,1000,500,100,50,10,1}; //환산할 돈의 종류


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package HW1_JAVA;
import java.util.Scanner//Scanner 클래스의 위치
class Sort{ //Sort 클래스 선언
    void sorting(int arr[], int gold){ //sorting 메소드 선언 인자 int형 배열 arr, int형 변수 gold
        int i;  int d;  //int형 변수 i, d 선언
        for(i=0;i<arr.length;i++//isms 0부터 배열 arr의 길이보다 작을 때까지
        {d=gold/arr[i]; //d는 gold를 arr[i]로 나눈 것의 몫
            if(d==0//d가 0이면 루프를 완전히 돌지 않고 i를 증가시킨 후 다시 돌게 만든다.
                continue;
            if(i<=2//i가 2 이하이면 원과 매로 출력
                System.out.println(arr[i]+"원권 "+d+"매");
            else  //i가 2초과이면 동전과 개로 출력
                System.out.println(arr[i]+"원짜리 동전 "+d+"개");
        gold%=arr[i];  // gold = gold % arr[i] 와 같다. (나머지)
        }    
    }
}
public class MoneyDivison { //class MoneyDivison 선언
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in); //Scanner 클래스 객체와 레퍼런스 변수 선언
        Sort so = new Sort(); //Sort 클래스 객체와 레퍼런스 변수 선언
        int []unit={50000,10000,1000,500,100,50,10,1}; // int형 배열 unit 선언과 초기화
        System.out.print("금액을 입력하세요>>");
        int gold=s.nextInt(); // int형 변수 gold 선언과 정수형 입력
        so.sorting(unit, gold); //sorting 메소드를 unit배열과 gold변수를 넣어 호출
    }
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
정수 오름차순 정렬기  (0) 2017.06.18
하위 문자 모두 출력하기  (0) 2017.06.18
반응형

2.5>Scanner를 이용하여 정수를 3개 입력 받고 이 3개의 수로 삼각형을 만들 수 있는지를 판별하라. 삼각형이 가능하려면 두 변의 합이 다른 한 변의 합보다 반드시 커야 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package HW1_JAVA; //패키지 이름
import java.util.Scanner// 스캐너 클래스의 위치
class triangle{    //triangle class 선언
    void make(int a, int b, int c){ //make 메소드, argument int형 변수 a,b,c
        int ar[]=new int[3]; int temp=0//int형 변수 ar[]선언(크기3), int형 변수 temp 선언및 초기화
        ar[0]=a;ar[1]=b;ar[2]=c; //배열 ar의 각 원소 초기화
        for(int i=0;i<3;i++)  //선택 정렬 알고리즘
        {
            for(int j=i+1;j<3;j++// 배열의 첫번째 원소부터 시작해 각각 한번씩 전부 비교한 후
            {// 뒤에 원소 크기가 피비교되는 원소보다 크면 둘의 자리를 바꿔준다
                if(ar[i]<ar[j])//다만 바로 바꿔주면 변수의 값 하나가 사라져 버리므로
                {            // 빈 물컵(temp)을 이용해 값을 교환해준다.
                    temp=ar[i];
                    ar[i]=ar[j];
                    ar[j]=temp;}}}
        if((ar[0]==0)||(ar[1]==0)||(ar[2]==0)) //변의 길이에 0을 입력한 경우 처리
            System.out.println("변의 길이는 0이 될 수 없습니다.");
        else if(ar[0]<ar[1]+ar[2]) // 삼각형의 형성 조건에 부합한 경우
            System.out.println("삼각형 세 변의 길이가 될 수 있습니다.");
        else //삼각형을 만들지 못한 경우
            System.out.println("삼각형 생성 불가능!!");
    }}
public class MakeTriangle {
    public static void main(String[] args) {
        int x=0int y=0int z=0;  //int 형 변수 x,y,z 선언 및 초기화
        Scanner s=new Scanner(System.in); // 레퍼런스 변수 s 와 Scanner 클래스의 오브젝트 생성
        triangle m=new triangle();//레퍼런스 변수 m과 triangle 클래스의 오브젝트 생성
        while(true){ // 무한 반복
        System.out.println("정수 3개를 입력하세요(-1 -1 -1은 종료)>>");
        x=s.nextInt(); y=s.nextInt(); z=s.nextInt(); //x,y,z를 int형으로 입력해준다.
        if((x==-1)||(y==-1)||(z==-1)) break// x,y,z가 -1일 경우 while문 탈출
        m.make(x, y, z);} //m이가리키는 오브젝트 내의 make 메소드 호출
    }}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

정수 오름차순 정렬기  (0) 2017.06.18
하위 문자 모두 출력하기  (0) 2017.06.18
직사각형 충돌  (0) 2017.06.18
윤년 판별기  (0) 2017.06.18
369 게임  (0) 2017.06.18
반응형

전화번호부를 구성하기 위하여 이름, 집전화번호, 휴대폰 번호로 구성되는 구조체를 정의한 후에 이 구조체의 배열을 선언하여 전화번호부를 구성한다. 5명의 데이터를 사용자로부터 받아서 저장하여 보라. 사용자로부터 이름을 입력받아서 전화번호를 검색하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <string.h>
#define SIZE 5
typedef struct phone{
    char name[20];
    char tel[20];
    char cell[20];
} PHONE;
void get_array(PHONE p[]);
void search(PHONE p[]);
int main(void)
{
PHONE p[SIZE];
get_array(p);
search(p);
return 0;
}
void get_array(PHONE p[])
{
int i;
for(i=0;i<SIZE;i++)
{
printf("이름을 입력하세요.");
scanf("%s", p[i].name);
printf("전화번호를 입력하세요.");
scanf("%s", p[i].tel);
printf("핸드폰번호를 입력하세요.");
scanf("%s", p[i].cell);}}
void search(PHONE p[])
{
    PHONE cmp;
    int i;
    while(1){
printf("이름을 입력하세요.(종료는 a)");
scanf("%s", cmp.name);
if(strcmp(cmp.name,"a")==0)
    break;
for(i=0;i<SIZE;i++)
{
    if(strcmp(cmp.name,p[i].name)==0)
    {
    printf("%s의 전화번호는 %s이고 핸드폰번호는 %s입니다.\n", p[i].name,p[i].tel,p[i].cell);
    break;
    }
}
if(i==5)
    printf("이름이 명단에 없습니다. 다시 입력하세요.\n");
}}
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C언어' 카테고리의 다른 글

삼각형, 사각형, 원  (0) 2017.01.02
포커 카드 배열  (0) 2016.12.28
직원 나이별 분류  (0) 2016.12.27
총 칼로리 구하기  (0) 2016.12.27
이메일 구조체  (0) 2016.12.27
반응형

학생들의 평점은 4.3점이 만점이라고 하자. 배열 grades[]에 학생 10명의 학점이 저장되어 있다. 이것을 100점 만점으로 변환하여서 배열 scores[]에 저장하는 함수를 작성하고 테스트하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#define SIZE 10
#define OUT 4.3
void convert(double *grades, double *scores, int size);
int main(void)
{
    double grades[SIZE]={3.7,4.3,3.6,0.7,1.1,2.1,3.1,4.0,3.0,2.0};
    double scores[SIZE]={0};
    int i;
    convert(grades,scores,SIZE);
    for(i=0;i<SIZE;i++)
        printf("학생%d 의 평점: %lf\n", i+1, grades[i]);
    for(i=0;i<SIZE;i++)
        printf("학생%d 의 점수: %lf\n", i+1, scores[i]);
 
 
}
void convert(double *grades, double *scores, int size)
{
int i;
for(i=0;i<size;i++)
{
*(scores+i)=*(grades+i)*(100/OUT);
}
}
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C언어' 카테고리의 다른 글

기본급과 보너스  (0) 2016.08.15
배열 복사  (0) 2016.08.15
배열 출력  (0) 2016.08.15
배열과 포인터  (0) 2016.08.15
정수의 합과 차  (0) 2016.08.15

+ Recent posts