인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

Lyw's profile image
Lyw

asked

[10 minutes a day | C++] Introduction to C++ programming that anyone can easily learn

데이터형변환이 안되요

Resolved

Written on

·

185

1

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

int a; a = 3.141592;

cout << (float)a << endl;

cout << float(a) << endl;

return 0;

} 비쥬얼 스튜디오로 했는데 데이터형변환이 안되고 3이 출력 되네요 문제가있나요??

C++

Answer 2

0

Lyw님의 프로필 이미지
Lyw
Questioner

그럼 인트형을 처음에 할당된 값은 강제로 형변환이 안되고 

플루트형만 형변환이 되는 건가요?? 짧게 할당된건 다시 길게 못하고 길게 할당된건 지울 수

있는 건가요??

 

 

 

 

 

 

 

 

 

 

 

pandacoding님의 프로필 이미지
pandacoding
Instructor

짧게 할당된 것을 다시 길게 늘리지 못하다기 보다는,

3.141592와 같은 소수점부가 포함된 수를

int형 변수로 저장하는 과정에서 이미 3만 저장됩니다.

이를 float형으로 출력하고자 한다해도, 애초에 저장된 수가 3이 끝이기 때문에

3만 출력되는 것입니다.

Lyw님의 프로필 이미지
Lyw
Questioner

감사합니다^^ 

 

0

pandacoding님의 프로필 이미지
pandacoding
Instructor

a는 int형 변수로 선언되어 있기 때문에,

값을 할당하는 과정에서 이미 "3"만 저장됩니다.

아래의 코드를 실행해보면 더 이해하기 쉬우실 것 같습니다 :)

 

#include <iostream>
#include <cstring>
using namespace std;

int main()

{

	int a = 3.141592;
	float b = 3.141592;

	cout << "int to int : " << (int)a << endl;
	cout << "int to float : " << (float)a << endl;
	cout << "float to int : " << (int)b << endl;
	cout << "float to float : " << (float)b << endl;

	return 0;

}
Lyw's profile image
Lyw

asked

Ask a question