The use of dots after numbers and division

I'm new to C++ and trying to understand someone else's code; they have a lot of dots in their code; some examples:

 
for (x=-5.; x<=-5/30.; x+=5/30.) {


 
A=A/(1.+B);


 
pow(10.,A)


There doesn't seem to be any consistency with the use of the dots and I can't find anything on the internet about what they do - any help much appreciated!
for (x=-5.; x<=-5/30.; x+=5/30.)

is the same as

for (x=-5; x<=-5/30; x+=5/30)

It's like the number 5 an be represented as 5.0, they both are the same value.

This code is not written well, and you should stay away from putting a . after every number. Us programmers love typing but we still try to do stuff with the least amount of keystrokes.

The dot operator calls a member of an object. You'll learn this later
 
object.member


(facepalm)x1000000000
Last edited on
ChajusSaib wrote:
for (x=-5.; x<=-5/30.; x+=5/30.)

is the same as

for (x=-5; x<=-5/30; x+=5/30)


No, it's not. The decimals are used to force floating point division. The second snippet uses integer division, and 5/30 in integer division is 0 - which makes that an infinite loop.
you might get a warning for precision loss ..
Hi,

When using floating point numbers (float or double) I always put digits on both side of the decimal point, as in 0.5, 5.0 , unless there is an exponent, 5e-3 say. To me, this makes it easier to see that the number is FP. Prefer to use double, unless you are using some graphics library that requires float, double is the default for c/c++. The precision of a float can be easily exceeded.

It's not a good idea to use FP numbers in loops like in the OP examples (because they are inexact), a better thing to do is to calculate how many times one needs to loop as an integer, then use that number in the loop.

Also, it is a good idea to not have magic numbers (like 5.0) in code, make them a const variable instead, then use the variable name in the code.

Where did you get that code? It may be a good idea to look at code from a reputable source, rather than random code from the internet. Also, make sure you are looking at c++ code, not c code - there are subtle differences. For example c++ has overloads for the pow function that takes integers as arguments, as well as double.

Finally, IIRC there was a proposal to have exact decimals for C++17. These are handy for calculations involving currency among other things. Hopefully people won't start to use them in loops though.

Good Luck, if you have any questions about anything just ask :+)

Topic archived. No new replies allowed.