Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ int float casting

Why is m always = 0? The x and y members of someClass are integers.

float getSlope(someClass a, someClass b) {                float m = (a.y - b.y) / (a.x - b.x);     cout << " m = " << m << "\n";     return m; } 
like image 496
el_pup_le Avatar asked Mar 28 '11 09:03

el_pup_le


People also ask

Can you cast an int to a float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00. The %.

What does casting int () do in C?

In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do. For instance, in case we assign a float variable (floating point) with an integer (int) value, the compiler will ultimately convert this int value into the float value.

Does C support type casting?

C programming language is best known for offering various types of functionalities and features to the programmers. C also allows the programmers to do type casting. Typecasting and Type conversion are different things. In C, typecasting is a way to simply change the data type of a variable to another data type.


2 Answers

You need to use cast. I see the other answers, and they will really work, but as the tag is C++ I'd suggest you to use static_cast:

float m = static_cast&lt float &gt( a.y - b.y ) / static_cast&lt float &gt( a.x - b.x );
like image 170
Kiril Kirov Avatar answered Oct 05 '22 17:10

Kiril Kirov


Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.

You'll want to cast the expressions to floats first before dividing, e.g.

float m = static_cast<float>(a.y - b.y) / static_cast<float>(a.x - b.x); 
like image 20
BoltClock Avatar answered Oct 05 '22 17:10

BoltClock