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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
// Example program
#include <iostream>
#include <limits>
#include <cmath>
// class to represent m*x + b
struct Linear {
double m, b;
};
// mx + b == nx + c
// mx == nx + (c - b)
// x(m - n) == (c - b)
// x = (c - b) / (m - n)
double solve(const Linear& expL, const Linear& expR)
{
double m_diff = expL.m - expR.m; // (m - n)
double b_diff = expR.b - expL.b; // (c - b)
if (m_diff == 0.0 && b_diff == 0.0)
{
return std::numeric_limits<double>::infinity();
}
if (m_diff == 0.0) // note: for non-integers, exact comparison with 0 can be inexact.
{ // Perhaps surround this with an epsilon
return std::numeric_limits<double>::quiet_NaN();
}
return b_diff / m_diff;
}
char signchar(double num)
{
return (num >= 0.0) ? '+' : '-';
}
std::ostream& operator<<(std::ostream& os, const Linear& expr)
{
if (expr.m != 0.0)
{
os << expr.m << 'x';
if (expr.b != 0)
{
os << ' ' << signchar(expr.b) << ' ' << std::abs(expr.b);
}
}
else if (expr.b != 0)
{
os << expr.b;
}
else
{
os << 0;
}
return os;
}
void display(const Linear& linA, const Linear& linB)
{
double x = solve(linA, linB);
std::cout << linA << " == " << linB;
if (std::isnan(x))
{
std::cout << ", No solution\n";
}
else if (std::isinf(x))
{
std::cout << ", Infinite solutions\n";
}
else
{
std::cout << ", x = " << x << '\n';
}
}
int main()
{
display( {4, -3}, {0, 1} );
display( {4, -3}, {0, -1} );
display( {4, 3}, {4, 0} );
display( {0, 3}, {0, 3} );
display( {4, 3}, {4, 3} );
display( {4, 3}, {0, 0} );
}
|