float 값에 "f"접미사?
C에서이 두 변수의 차이점이 무엇인지 궁금합니다.
float price = 3.00;
과
float price = 3.00f;
후행 "f"?
3.00A와 해석 double에 반대, 3.00fA와 컴파일러에 의해 볼 수있는 float.
f접미사는 단순히입니다 컴파일러에 지시 float하고있는입니다 double.
참조 MSDN (C ++)
이미 말한 것 외에도 1.0 대 1.0f를 추적하는 것은 많은 사람들이 생각하는 것보다 더 중요합니다. 다음과 같은 코드를 작성하면 :
float x;
...
float y = x * 2.0;
2.0은 double이기 때문에 x는 double로 승격됩니다. 컴파일러는 해당 프로모션을 최적화 할 수 없거나 C 표준을 위반합니다. 계산은 배정 밀도로 수행되고 결과는 암시 적으로 실수로 잘립니다. 즉, 2.0f 또는 2를 작성했을 때보 다 계산이 더 느리지 만 (더 정확하지만) 느립니다.
2를 작성했다면 상수는 int 유형이되며 이는 float로 승격되며 계산은 "float precision"으로 수행됩니다. 좋은 컴파일러는이 프로모션에 대해 경고합니다.
여기에서 "일반적인 산술 변환"규칙에 대해 자세히 알아보십시오.
http://msdn.microsoft.com/en-us/library/3t4w2bkb%28v=vs.80%29.aspx
접미사가없는 부동 소수점 리터럴은 double이고 반올림은 작은 리터럴도 float 및 double로 반올림 할 때 다른 값을 가질 수 있기 때문입니다. 다음 예에서이를 확인할 수 있습니다.
float f=0.67;
if(f == 0.67)
printf("yes");
else
printf("no");
float로 반올림 할 때 값이 double로 반올림 될 때와 다르기 no때문에 출력됩니다 0.67. 반면에 :
float f=0.67;
if(f == 0.67f)
printf("yes");
else
printf("no");
출력 yes.
접미사는 대문자 또는 소문자를 사용하여 지정할 수 있습니다.
이것을 또한 시도하십시오 :
printf(" %u %u\n", sizeof(.67f), sizeof(.67));
@ codepade 확인
3.00은 double이고 3.00f는 float입니다.
컴파일러가 어쨌든 double 상수를 float로 변환하기 때문에 종종 차이가 중요하지 않습니다. 그러나 다음을 고려하십시오.
template<class T> T min(T a, T b)
{
return (a < b) ? a : b;
}
float x = min(3.0f, 2.0f); // will compile
x = min(3.0f, 2); // compiler cannot deduce T type
x = min(3.0f, 2.0); // compiler cannot deduce T type
That's because the default type of a floating point numeric literal - the characters 3.00 is double not float. To make this compile you have to add the suffix f (or F).
Adding few more combination of comparisons between float and double data types.
int main()
{
// Double type constant(3.14) converts to Float type by
// truncating it's bits representation
float a = 3.14;
// Problem: float type 'a' promotes to double type and the value
// of 'a' depends on how many bits added to represent it.
if(a == 3.14)
std::cout<<"a: Equal"<<std::endl;
else
std::cout<<"a: Not Equal"<<std::endl;
float b = 3.14f; // No type conversion
if(b == 3.14) // Problem: Float to Double conversion
std::cout<<"b: Equal"<<std::endl;
else
std::cout<<"b: Not Equal"<<std::endl;
float c = 3.14; // Double to Float conversion (OK even though is not a good practice )
if(c == 3.14f) // No type conversion
std::cout<<"c: Equal"<<std::endl; // OK
else
std::cout<<"c: Not Equal"<<std::endl;
float d = 3.14f;
if(d == 3.14f)
std::cout<<"d: Equal"<<std::endl; // OK
else
std::cout<<"d: Not Equal"<<std::endl;
return 0;
}
Output:
a: Not Equal
b: Not Equal
c: Equal
d: Equal
참고URL : https://stackoverflow.com/questions/5026570/suffix-of-f-on-float-value
'Program Club' 카테고리의 다른 글
| gradle.properties와 settings.gradle을 언제 사용합니까? (0) | 2020.11.14 |
|---|---|
| Haskell 기능이 정확성 속성으로 입증 / 모델 검사 / 검증 될 수 있습니까? (0) | 2020.11.14 |
| C ++에서 개체 파괴 (0) | 2020.11.14 |
| 'catch'블록없이 'try-finally'블록 사용 (0) | 2020.11.14 |
| 백본 모델에서 초기화와 생성자의 차이점은 무엇입니까 (0) | 2020.11.14 |