Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always necessary to use float literals when performing arithmetic on float variables in C++?

I see a lot of C++ code that has lines like:

float a = 2;
float x = a + 1.0f;
float b = 3.0f * a;
float c = 2.0f * (1.0f - a);

Are these .0f after these literals really necessary? Would you lose numeric accuracy if you omit these?

I thought you only need them if you have a line like this:

float a = 10;
float x = 1 / a;

where you should use 1.0f, right?

like image 813
Joan Venge Avatar asked Sep 21 '12 18:09

Joan Venge


People also ask

What is floating-point arithmetic in C?

A "floating-point constant" is a decimal number that represents a signed real number. The representation of a signed real number includes an integer portion, a fractional portion, and an exponent. Use floating-point constants to represent floating-point values that can't be changed.

Should I use double or float in C?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float.

Can floats be literals?

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

Are there floats in C?

Real numbers are represented in C by the floating point types float, double, and long double. Just as the integer types can't represent all integers because they fit in a bounded number of bytes, so also the floating-point types can't represent all real numbers.


1 Answers

You would need to use it in the following case:

float x = 1/3;

either 1 or 3 needs to have a .0 or else x will always be 0.

like image 101
Borgleader Avatar answered Nov 14 '22 16:11

Borgleader