[C++] 코드 작성 실수 모음

JUN·2024년 4월 20일

실수형 연산

  • 실수형 연산은 "=="은 위험하다
  • 이는 float, double 과 같은 실수형 자료는 부동소수점 형태로 구현되어있어 발생하는 문제이다.
  • 저 소수점 한참 아래의 오차값이 발생하기 때문이다.
#include<iostream>
#include<string.h>
using namespace std;
double c[10];
double DP(int d) {
	if (d == 10) return 1;
	double& ret = c[d];

	if (ret != -1) return ret;

	ret = 0.0;
	ret += DP(d + 1) * 0.1;
	return ret;
}
int main() {
	memset(c, -1, sizeof(c));
	cout << DP(0) << "\n";
}

크기 차이로 조절하여 다음과 같은 코드로 변경하여 문제를 해결할 수 있다

#include<stdio.h>
#include<string.h>
using namespace std;
double c[10];
double DP(int d) {
	if (d == 10) return 1;
	double& ret = c[d];

	if (ret > -1) return ret;

	ret = 0.0;
	ret += DP(d + 1) * 0.1;
	return ret;
}
int main() {
	memset(c, -1, sizeof(c));
	printf("%.10lf", DP(0));
}

실수 Bool

#include<iostream>
using namespace std;

int c = 1
if(c){
	cout << "True" << "\n";
}
else{
	cout << "False" << "\n"; 
}

True가 출력될까 False가 출력될까?
답은 True이다 c가 0 이 아니면 모두 True가 나옴을 기억하자

한 줄 if문

int c = (조건, 비교연산자) ? (True일 땐 이거) : (False일 땐 이거)

  • Example
int a = 1;
int c = (a == 1) ? 1 : 0;
cout << c << "\n";
  • c 값은?
    답은 1이겠죵 이유는 "a == 1"의 조건이 True이기 때문!!
profile
기록

0개의 댓글