view raw
maxloo2 maxloo2 - 8 months ago 30
C++ Question

Calculate using int and output float?

//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 << answer << std::endl;
//alternative= std::cout << fixed << setprecision(#) << answer << std::endl;


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
for variables I declared for the coordinates, the result of the calculation would output as
with decimals. However, I wonder if I may still use
for user input so that I can ensure the inputs are integers.

Extra question: Would it be possible to convert a
presented in the form of "#.##" to "# #/#"? More like how we do mathematics IRL.


You can use implicit conversion to double:

answer = (b-d)/(a-c*1.0); 

Or explicit cast:

answer = (b-d)/(a-(float)c);