I dont know how long I've been trying to figure this out but I havent got to an answer.... I believe that there must be a way of converting an integer to a double or visa versa but I cant think how... I always thought parseInt or parseDouble wud work well on C++ but all it does is giving me errors... I guess thats a Java syntax not C++ can anyone help me

if i'm not wrong you can directly assign an integer to a double in c++, there's no need to do an explicit casting.

It's called "typecasting".

int a = 5;
double b = (double) a;
double c = 4.0;
int d = (int) c;

chandra.rajat is correct in many cases. The compiler will figure out the typecasting above without being told and unlike Java, C++ doesn't demand all of the explicit conversions. It figures out what it can and gives warnings instead of errors, unlike Java. Often it's unnecessary, but sometimes it makes a difference (generally when what is to be typecasted is NOT going to be assigned to a variable with a type like above), as in the two examples below:

int a = 7;
cout << ((double) a / 2); // typecasting

The above yields 3.5, or 7.0/2 (floating point division)

int a = 7;
cout << (a / 2); // no typecasting

The above yields 7/2 = 3 (integer division).
Put the type that you want to convert TO in parentheses before the number/variable to be converted. Note. In the example above, a remains an integer with value 7 in both cases.

c++ has other more dependable typecasting. C-style typecasting can let you kill yourself if you don't know exactly what you are doing, such as in this example attempting to typecast to normally incompatible data types.

double a = 12.34;
char* b = (char *)&a;
int c = (int)b;

In c++ if you use static_cast you will get a compiler error int d = static_cast<int>(b); // <<<< Error here

Can you ellaborate static_cast why and when do u use it coz I have seen it most of the time and alwayz wander what is it for

This article has been dead for over six months. Start a new discussion instead.