백준 - 25206번 너의 평점은(map, 문자열)

Kiwoong Park·2023년 5월 23일
0

문제

간단한 구현 문제로 등급별로 점수를 매기면 된다.


C++ 풀이

파이썬의 dictionary 같은 자료형이 C++에 map 자료형과 비슷하여 써봤다.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<string,float> m;
    m["A+"]= 4.5;
    m["A0"]= 4.0;
    m["B+"]= 3.5;
    m["B0"]= 3.0;
    m["C+"]= 2.5;
    m["C0"]= 2.0;
    m["D+"]= 1.5;
    m["D0"]= 1.0;
    m["F"]= 0.0;
    
    int n;
    string s,g;
    float a,tot;
    while(cin >> s >> a >> g){
        if (g == "P") continue;
        tot+=a*m[g];
        n+=a;
    }
    cout << tot/n;

    return 0;
}

숏코딩 분석하기

역시나 이게 같은 기능을 하는 코드인지 싶은 암호문과 같은 코드..

#include <stdio.h>
int n,t,s,S,i;
char x[99];
int main(){
	for(;i++<20;){  // 문제를 읽어보면 20줄에 걸쳐서 입력이 주어진다.
		scanf("%s %d.%d %s",x,&n,&t,x);
        /* scanf를 통해 string, 두 개의 integer를 
        '.'(dot)으로 구분하여 각각 n과 t에 저장하고 
        마지막 string을 x로 받는다.  
        */
		if(*x==80) continue; // the first character(`*x`)가 80, 즉 'P'에 해당한다.
		S+=n,t=*x>68?0:69-*x,t=t*10+(x[1]&&x[1]-48?5:0),s+=n*t;
	}
	printf("%lf",(double)s/S/10);
}
// 가독성을 위해 나눠서 설명해보자
S+=n // n은 학점으로, 이후 평균을 구하기 위해 S 변수에 누적하여 더한다. Ex. S=3+4+...
t=*x>68?0:69-*x // 68은 ASCII 값으로 'D'에 해당하여 첫 문자가 D 
// 다음인 F이면 0점, A, B, C인 경우 변수 `t`에 각각 4, 3, 2점을 저장한다.
t=t*10+(x[1]&&x[1]-48?5:0)
/* x[1]는 '+' 아니면 '0'이므로 AND(&&) 연산을 해서 '0'인 경우에 해당하는 48을 빼서 false 일 때는 0을 더하고, true일 경우 5를 더한다.
만약, 학점이 A+여서 t가 4이면 t=45가 되는 식
즉, 소문자 s = 45*3학점 + 25*4학점 + ... 
각각 10을 곱한 크기이므로 소문자 s/대문자S/10을 하면 학점 평점이 나온다.
*/
s+=n*t;

*x ?

  • 연산은 메모리로의 접근을 나타내며, *xx라는 포인터 변수가 가리키고 있는 메모리에 접근한다는 의미이다. x는 character array이므로 메모리에 접근한다는 것은 첫 번째 문자에 접근한다는 의미이므로 *x는 첫 문자를 나타낸다.

In C, an array name without an index is treated as a pointer to the first element of the array. So, x represents the address of the first element of the character array. By dereferencing the pointer using the operator (x), we can access the value stored at that memory location, which in this case corresponds to the first character of the string stored in x.

Therefore, *x is used to refer to the value of the first character in the character array x.

profile
You matter, never give up

0개의 댓글