I'm trying to teach myself C++ from Stroustrup's Principles and Practice Using C++ (second edition) and I've gotten to the drill in chapter 4. The problem tells me to make a program that takes in a number with a unit of either feet, inches, meters, and centimeters, as well as log the largest and smallest numbers the user has input. I got the code to work by initializing my smallest number as 0 and making an if
statement check if the input was smaller or 0 (because you can't really have 0 length).
Is there a way to either start with an infinitely larger "smallest number" variable so it always changes it in the if
statement, or a way to where it has to do as few if
statements as possible? Also, I'd rather not ask for an initial starting number before the while
loop.
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please input a number followed by a unit (cm, m, in, ft). Results are read in meters. Input a '|' to terminate the program." << endl;
double x;
string unit = " ";;
constexpr double cm = .01;
constexpr double in = .0254;
constexpr double ft = .3048;
double smallest = 0;
double largest;
double sum = 0;
while(cin >> x >> unit)
{
if((char)x == '|')
break;
cout << "Value entered: " << x << unit << endl;
if(unit=="m" || unit=="cm" || unit=="in" || unit=="ft") //converts units to meters
{
if(unit == "m")
{
x=x; //
}
else if(unit == "cm")
{
x*=cm;
}
else if(unit == "in")
{
x*=in;
}
else if(unit == "ft")
{
x*=ft;
}
else
cout << "Something went wrong." << endl;
if(x > largest)
{
largest = x;
}
if(x < smallest || smallest == 0)
{
smallest = x;
}
cout << "The smallest number so far is: " <<smallest<< " meters\n";
cout << "The largest number so far is: " << largest << " meters\n";
sum+=x;
}
else
cout << "Invalid unit! Try again." << endl;
}
cout << "The sum of all lengths is: " << sum << " meters\n";
}