I'm wondering if there is a way I can combine the two Convert functions into one. So for instance instead of having a ConvertFt and ConvertIn function, just having one Convert function. Thanks!
what I am saying is that the code can't tell that what you handed it is in inches, feet, or furlongs. Its just a number. To get the conversion factor right you have to know what it is, and that means having its units ride along with it. You had that implicitly before by calling the right function, but to roll them into one, it now has to be explicit.
Another way to do it would be to not have functions at all.
enum units {inches,feet, meters, etc, maxunits}
double convert[maxunits] = {0.3048,2.54,etc...}; //values match position above, so first one is for inches, second for feet, ... etc
result = input*convert[inches];
I highly recommend you make the conversion factors have both sides. that is name them inches_to_meters or meters_to_furlongs so you know exactly what you have and what you get.
@jonin
I see what you are saying in the first part. I am defining it as a function because that is what is asked of me in the HW problem, I should have specified that. But I do understand what you mean by the if else statement, and differentiating between the two by changing their data types. Thanks!
Whenever I input it as an or statement it doesn't seem to work. For instance i'll type in 'n' and it will just run the program again. The compiler gives me this error "(<expression> || <non-zero constant>) is always a non-zero constant."
Edit: Nevermind I figured it out, thanks for the clarification bro.
fyi:
if(ans == 'y' || 'Y')
says
if ans == y or true, because 'Y' is an integer, and its not zero, to the compiler.
(x) or (true) is just (x), the or true part is redundant and ignored.
this is why it will compile and not work, even though it is not remotely like what you intended.
As jonnin first said "depends on what you mean and want."
You could keep it simple with:
1 2 3 4 5
// <--- Function call.
Convert(Feet, Inches, Meters, Centimeters);
// <--- Function definition.
void Convert(int Feet, int Inches, double& Meters, double& Centimeters)
I try to add to what jonnin said.
while (ans == 'y' && 'Y');. If "y" was entered then the lhs of && would be true and the rhs is always true because the value of "Y" is not zero. So the expression evaluates to true. If "ans" has anything other than "y" the lhs is false and as a logical "AND" the rhs is never evaluated because the lhs is false and the whole can never evaluate to true.
In something like this I have always seen and used while (ans == 'y'|| ans == 'Y'); to test for either case. As a logical "OR" only one side has to be true for the whole to be true.
An alternative would be while (std::toupper(ans)== 'Y'); // Requires header file "cctype". Or you could use "tolower" to change the case. With either function if the case does not need to be changed nothing happens. Also if "ans" does not contain a letter nothing happens.