Reputation: 35
//findSlope(twoPoints).exe
//finding the slope of line AB, using coordiantes of point A and B.
#include <iostream>
int main()
{
int a, b, c, d;
float answer;
std::cout << "The X coordiante of A: ";
std::cin >> a;
std::cout << "\nThe Y coordiante of A: ";
std::cin >> b;
std::cout << "\nThe X coordiante of B: ";
std::cin >> c;
std::cout << "\nThe Y coordiante of B: ";
std::cin >> d;
std::cout << "\nThe slope of line AB = " << std::endl;
answer = (b-d)/(a-c);
std::cout.setf(std::ios::fixed);
std::cout.precision(3);
std::cout << answer << std::endl;
//alternative= std::cout << fixed << setprecision(#) << answer << std::endl;
std::cout.unsetf(std::ios::fixed);
return 0;
}
I am learning C++ and I tried to code a program that calculate the slope using the coordinates of two points.
I understand that if I use float
for variables I declared for the coordinates, the result of the calculation would output as float
with decimals. However, I wonder if I may still use int
for user input so that I can ensure the inputs are integers.
Extra question: Would it be possible to convert a float
presented in the form of "#.##" to "# #/#"? More like how we do mathematics IRL.
Upvotes: 2
Views: 4137
Reputation: 1
You can use int
for user input, but to precisely calculate anything that contains a division operator /
, you'll need to cast to floating point types.
It's usually considered a good practice in C++ to use static_cast
for that (although you still may use c-style (float)
syntax).
For example:
answer = static_cast<float>(b - d) / (a - c);
Here, you convert (b - d)
to float
and then divide it by integer, which results in a float
.
Note that the following wouldn't work correctly:
answer = static_cast<float>((b - d) / (a - c));
The reason is that you first divide an int
by another int
and then convert the resulting int to a float
.
P. S. float
is really inaccurate, so I would advise to use double
instead of float
in all cases except where you want to write faster code that does not depend on mathematical accuracy (even though I'm not sure it would be faster on modern processors) or maintain compatibility with an existing library that uses float
for some of its functions.
Upvotes: -1
Reputation: 29431
You can use implicit conversion to double:
answer = (b-d)/(a-c*1.0);
Or explicit cast:
answer = (b-d)/(a-(float)c);
Bonuses:
Upvotes: 2