Reputation: 7
I'm working through Stroustrup's Programming - Principles and Practice using C++ currently. At the end of Chapter 4, there is a drill that asks you to start writing a program, and alter it one step at a time as you go down the line. I am at a step where, at this point, the program should:
So far, everything seems to be working, except that it won't output if the last entry is the smallest so far. What am I doing wrong?
double convert(double num, string type);
constexpr double centimeters_per_meter = 100;
constexpr double centimeters_per_inch = 2.54;
constexpr double inches_per_foot = 12;
int main()
{
cout << "Please enter a number and a unit (cm, m, in, ft): \n";
double x;
string unit;
double smallest = 0, largest = 0;
while (cin >> x >> unit) {
double x_in_meters = convert(x, unit);
if (x_in_meters < smallest && x_in_meters != 0) {
cout << "\nThis is the smallest number so far!\n";
smallest = x_in_meters;
}
else if (x_in_meters > largest && x_in_meters != 0) {
cout << "\nThis is the largest number so far!\n";
largest = x_in_meters;
}
else {}
}
return 0;
}
double convert(double num, string type)
{
double num_in_meters = 0.0;
if (type == "cm") {
num_in_meters = num / centimeters_per_meter;
cout << num << " " << type << " is " << num_in_meters << " meters\n";
return num_in_meters;
}
else if (type == "m") {
num_in_meters = num;
cout << num_in_meters << " meters\n";
return num_in_meters;
}
else if (type == "in") {
num_in_meters = num * centimeters_per_inch / centimeters_per_meter;
cout << num << " " << type << " is " << num_in_meters << " meters\n";
return num_in_meters;
}
else if (type == "ft") {
num_in_meters = num * inches_per_foot * centimeters_per_inch / centimeters_per_meter;
cout << num << " " << type << " is " << num_in_meters << " meters\n";
return num_in_meters;
}
else {
cout << "I don't understand " << type << " as a unit\n";
return 0;
}
}
Upvotes: 0
Views: 97
Reputation: 481
The best way to solve these kind of logic errors is to go through your code in your head with an example value. So let's trace through your code:
To solve this, a good solution is to set both smallest and largest to the first value that is processed. This has many benefits:
If you only input in 1 value total, then that value technically is both the smallest and largest.
If you input two values: after going through the first one, the program will set both smallest and largest to the first value. As it considers the second value, it will decide if it is smaller or larger. Once again, this works.
For any value size greater, we know our code works now.
Upvotes: 1
Reputation: 6831
You are initializing smallest
as zero, so the only way you'll get a smaller value is if you enter a negative number.
You should use a bool
variable indicating if you've entered any values yet or not. And when you get the first value, set both smallest
and largest
to that value.
Upvotes: 0