problem with cmath/static cast

I'm supposed to use cmath functions & static_cast to calculate the midpoint and distance between two coordinates. My program is running without errors but the answers it gives are absurdly large. I know I'm using the right equations because they were given on the assignment, so apparently I'm using the functions or static cast wrong, but I can't seem to find the error. Help would be appreciated...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
    int x1, x2, y1, y2;
    double distance, xmid, ymid;
    cout << fixed << showpoint;

    distance = sqrt(
            static_cast<double>(
                pow(x1 - x2, 2) + pow(y1 - y2, 2)));
    xmid = static_cast<double>(x1 + x2) / 2;
    ymid = static_cast<double>(y1 + y2) / 2;

You did not assign any values for variables x1, x2, y1, and y2. So the result is undefined.
Since pow returns double the cast is not necessary. See:

http://cplusplus.com/reference/cmath/pow/?kw=pow
Thanks coder, I made that fix, but i'm still getting bad output like this:

The distance between (1, 1) and (-1, -1) is 182230660.000097
Their midpoint is located at (-68559849.000000, 2686822.000000)


Here is the entire program in its current version, since maybe the problem is elsewhere:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
    int x1, x2, y1, y2;
    double distance, xmid, ymid;
    cout << fixed << showpoint;

    distance = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
    xmid = static_cast<double>(x1 + x2) / 2;
    ymid = static_cast<double>(y1 + y2) / 2;

    cout << "This program will calculate the distance between\n"
            << "and the midpoint of two coordinates.\n"
            << "Please type in values for x [space] y and hit enter." << endl
            << "x and y may be positive or negative integers." << endl;
    cin >> x1 >> y1;
    cout << "Now please enter a second set of coordinates." << endl;
    cin >> x2 >> y2;
    cout << "\nThe distance between (" << x1 << ", " << y1 << ") and ("
            << x2 << ", " << y2 << ") is " << distance << endl;
    cout << "Their midpoint is located at (" << xmid << ", " << ymid << ")" << endl;

    return 0;
}




The problem is that you compute distance, xmid and ymid before asking the user what their values are.
Thanks, it's working now.
Topic archived. No new replies allowed.