Sub String Logic

This is an example of how sub string and math can be used to make logical decisions without using if/elses or switches. It works because of this equation
(x + |x|)/x = 2 if x > 0 and = 2 if x < 0.


#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
//declaration of variables
double gallonsOfGas = 0;
double milesPerGallon = 0;
double distance = 0;
string answer = " not";
double x = 0;
double n = 0;

//user prompt
cout << "Enter the gallons of gas in the tank: ";
cin >> gallonsOfGas;
cout << '\n' << "Enter the fuel efficiency in miles per gallon: ";
cin >> milesPerGallon;
cout << '\n' << "Enter the distance you want to travel: ";
cin >> distance;
cout << '\n';

//math part
x = distance - gallonsOfGas * milesPerGallon;
n = (x + fabs(x)) / x;
cout << n << endl;

//whether you will make it or not
cout << "You will" + answer.substr(0, 2 * n ) + " make it.";
return 0;
}
(x + |x|)/x = 2 if x > 0 and = 2 if x < 0.
I'd think you mean '= 0 if x < 0'

Your program will crash in case of x == 0
Topic archived. No new replies allowed.