Coding Problems and Errors:



Thursday, January 21, 2010

Rounding a number without "if"s


Rounding a "double" number without using "if" statements

double num;
int num_rounded = static_cast<int>(floor(num+0.5));
Back to Top


Uniform (Pseudo) Random [0,1] Probability distribution in C++


Generating Uniform (Pseudo) Random Probability distribution in the interval [0,1] in C++:

double p = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
--or--
double p = rand() / static_cast<double>(RAND_MAX);

Of course, use #include<cstdlib> for using int rand(); function and use void srand(int); to set the seed (if necessary).

Debugging tip:
---------------
Using a specific seed initially can help with repeating the random number patterns. Eg: srand(5); can be used in the program for debugging purposes and then removed later on!
Back to Top


C++ Coding tips


End your programs with a newline to make them portable.
cout << "\n";
-----

Use cerr instead of cout for displaying error messages
-----

Use enum types instead of defining constants (when appropriate). However, do not treat them as integers (i.e. do not use arithmetic operators on them, etc.)
Back to Top


C++ Order of evaluation


Better not to assume the order of evaluation in a C++ subexpressions. Also do not use ++ and -- operators as part of subexpressions (Eg: n + (++n))

Guaranteed order: Subexpressions using AND(&&) OR(||) and COMMA(,) operators are always evaluated in left-to-right manner. Helps with "Short-circuit evaluation" for relational operators!

General order:
Unary operator: right-to-left
Assignment: right-to-left Eg: a = b = c; OR a = (b = c);
Binary operator: left-to-right


Back to Top


Typecasting in C++


static_cast<type>(Expression) 
dynamic_cast<type>(Expression) 
const_cast<type>(Expression) 
reinterpret_cast<type>(Expression)  

static cast alternatives (not recommended): 
(type) Expression 
type(Expression)  
Eg: static_cast<double>(3) || double(3) || (double) 3
Back to Top


 

Labels