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; }
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 %.
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.
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.
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< float >( a.y - b.y ) / static_cast< float >( a.x - b.x );
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With