Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about typecast behavior in arithmetic

I have the following code. My main question lies in line 5.

int x1 = extRes1.at(1).toInt();   //A fairly large int value. This is from Qt, where extRes is a QStringList. the key is, the function returns an int value.
int x2 = extRes2.at(1).toInt();
int y1 = extRes1.at(2).toInt();
int y2 = extRes2.at(2).toInt();
double c = (double)(y2*x1-y1*x2)/(x1-x2);   //Typecasting, as I want this arithmetic to return a floating point properly.

My question is, what is the exact behavior of the typecasting on line 5?
Based on what I’ve found on the topic so far, I believe that the result of Line 5 RHS (y2 *x1-y1 * x2)/(x1-x2) is represented by a double. But does typecasting work by turning all individual elements (such as y2, x1) in the arithmetic into the type (in this case double)? Or does it work by only converting the result of the final solution?

I am aware that on a technical level, my issue can be solved by converting the preexisting ints to doubles. Please let me know if more information is required.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Only the result of (y2*x1-y1*x2) (which is an int) is converted to double.

This is due to the precedence of the casting operator:
As you can see here, casting is priority over all "normal" artihmetic operations like multiplication and division.

Then this double is divided by the result of (x1-x2) (an int promoted to double for the division) using floating-point division, yielding the double result assigned to c.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading