106k views
3 votes
need to be in C++ language. Write a program that asks a user for two points that are whole numbers as input (assume the user inputs the correct data, in other words, you do not have to validate this input). Store the first point in the variables X1 and Y1. Store the second point in X2 and Y2. Create two user-defined functions. One function should return the midpoint of the line. The second function should return the slope of the line. Display the returned values to the monitor appropriately labeled

User JyoonPro
by
7.0k points

1 Answer

0 votes

Final answer:

To write a program in C++ that calculates the midpoint and slope of a line between two points, follow these steps: ask the user for the coordinates of the two points, create separate functions to calculate the midpoint and slope, and display the results.

Step-by-step explanation:

To write a program in C++ that calculates the midpoint and slope of a line between two points, you can follow these steps:

  1. Ask the user to input the coordinates for the two points, storing them in variables X1, Y1, X2, and Y2.
  2. Create a function, let's call it calculateMidpoint, that takes the coordinates as input and returns the midpoint of the line. The midpoint can be calculated by finding the average of the x-values and the average of the y-values.
  3. Create another function, let's call it calculateSlope, that takes the coordinates as input and returns the slope of the line. The slope can be calculated by finding the difference in y-values divided by the difference in x-values.
  4. In the main function, call these two functions to calculate the midpoint and slope, and then display the results to the user.

Here's an example program that implements these steps:

#include <iostream>

using namespace std;

struct Point {
int x;
int y;
};

Point calculateMidpoint(Point p1, Point p2) {
Point midpoint;
midpoint.x = (p1.x + p2.x) / 2;
midpoint.y = (p1.y + p2.y) / 2;
return midpoint;
}

float calculateSlope(Point p1, Point p2) {
float slope = static_cast<float>(p2.y - p1.y) / (p2.x - p1.x);
return slope;
}

int main() {
Point p1, p2;
cout << "Enter the coordinates of the first point (x y): ";
cin >> p1.x >> p1.y;
cout << "Enter the coordinates of the second point (x y): ";
cin >> p2.x >> p2.y;
Point midpoint = calculateMidpoint(p1, p2);
float slope = calculateSlope(p1, p2);
cout << "Midpoint: (" << midpoint.x << ", " << midpoint.y << ")" << endl;
cout << "Slope: " << slope << endl;
return 0;
}

User Sachin Janani
by
7.7k points