Post

[백준BOJ25304 C++] 영수증

[백준BOJ25304 C++] 영수증

문제

https://www.acmicpc.net/problem/25304


풀이

변수 선언시 0으로 초기화하지 않으면 오답이 된다.

변수를 선언했을 때 초기화를 하지 않는다면 쓰레기값이 담는다. 초기화한 상태에서 sum += a * b; 같은 연산을 한다면 쓰레기값에서 더해진다. 오류가 발생할 수도 있고, 정상적인 작동을 위해선 초기화가 필요하다.


제출

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() {
	int X, N, a, b;
	int sum = 0;
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> X;
	cin >> N;
	
	for (int i = 0; i < N; i++) {
		cin >> a >> b;
		sum += a * b;
	}

	if (sum == X) cout << "Yes";
	else cout << "No";
	return 0;
}

제출했던 오답 코드 ``` #include using namespace std;

int main() { long X; int N, a, b, sum; ios_base::sync_with_stdio(false); cin.tie(NULL);

1
2
3
4
5
6
7
8
9
10
11
cin >> X;
cin >> N;

for (int i = 0; i < N; i++) {
	cin >> a >> b;
	sum += a * b;
}

if (sum == X) cout << "Yes";
else cout << "No";
return 0; } ``
This post is licensed under CC BY 4.0 by the author.