Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of a ".f" appended to a number?

I saw 1/3.f in a program and wondered what the .f was for. So tried my own program:

#include <iostream>  int main() {     std::cout << (float) 1/3 << std::endl;     std::cout << 1/3.f << std::endl;     std::cout << 1/3 << std::endl; } 

Is the .f used like a cast? Is there a place where I can read more about this interesting syntax?

like image 641
Nav Avatar asked Jan 28 '11 12:01

Nav


People also ask

What is difference between float and double in C++?

double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

What does F behind a number mean?

It usually tells the compiler that the value is a float , i.e. a floating point integer. This means that it can store integers, decimal values and exponentials, e.g. 1 , 0.4 or 1.2e+22 . Follow this answer to receive notifications. answered Nov 17, 2011 at 12:50.

What does 0 f mean c++?

. 0 is floating point, f is type float specifically.

Why add f to float c++?

A floating-point-literal-suffix (f or F for float, l or L for long double) can be used when we want to specify the type of a floating point literal; the type of a floating point literal without a suffix is double.


2 Answers

3. is equivalent to 3.0, it's a double.

f following a number literal makes it a float.

like image 73
peoro Avatar answered Sep 17 '22 00:09

peoro


Without the .f the number gets interpreted as an integer, hence 1/3 is (int)1/(int)3 => (int)0 instead of the desired (float)0.333333. The .f tells the compiler to interpret the literal as a floating point number of type float. There are other such constructs such as for example 0UL which means a (unsigned long)0, whereas a plain 0 would be an (int)0.

The .f is actually two components, the . which indicates that the literal is a floating point number rather than an integer, and the f suffix which tells the compiler the literal should be of type float rather than the default double type used for floating point literals.

Disclaimer; the "cast construct" used in the above explanation is not an actual cast, but just a way to indicate the type of the literal.

If you want to know all about literals and the suffixes you can use in them, you can read the C++ standard, (1997 draft, C++11 draft, C++14 draft, C++17 draft) or alternatively, have a look at a decent textbook, such as Stroustrup's The C++ Programming Language.

As an aside, in your example (float)1/3 the literals 1 and 3 are actually integers, but the 1 is first cast to a float by your cast, then subsequently the 3 gets implicitly cast to a float because it is a righthand operand of a floating point operator. (The operator is floating point because its lefthand operand is floating point.)

like image 27
wich Avatar answered Sep 17 '22 00:09

wich