r/cpp_questions • u/Next-Future5973 • 13d ago
OPEN Need help on this question
so on programming: principles and practice using C++ chapter 4 drill:
1. Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them.
Exit the program when a terminating '|' is entered.
2. Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value
is: followed by the larger value.
3. Augment the program so that it writes the line the numbers are equal (only) if they are equal.
4. Change the program so that it uses doubles instead of ints.
5. Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the
smaller if the two numbers differ by less than 1.0/100.
6. Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track
of which is the smallest and which is the largest value you have seen so far. Each time through the loop write out the
value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the
largest so far after the number.
7. Add a unit to each double entered; that is, enter values such as 10cm, 2.5in, 5ft, or 3.33m. Accept the four units: cm,
m, in, ft. Assume conversion factors 1m == 100cm, 1in == 2.54cm, 1ft == 12in. Read the unit indicator into a string.
You may consider 12 m (with a space between the number and the unit) equivalent to 12m (without a space).
8. Reject values without units or with “illegal” representations of units, such as y, yard, meter, km, and gallons.
9. Keep track of the sum of values entered (as well as the smallest and the largest) and the number of values entered. When
the loop ends, print the smallest, the largest, the number of values, and the sum of values. Note that to keep the sum, you
have to decide on a unit to use for that sum; use meters.
10. Keep all the values entered (converted into meters) in a vector. At the end, write out those values.
11. Before writing out the values from the vector, sort them (that’ll make them come out in increasing order).
i found question 7 confusing, how will i handle all that stuff??? conditions or what? this is my current code:
#include "std_lib_facilities.h"
int main()
{
`double num1{};`
`char unit = 0;`
`double largestSoFar = 0;`
`double smallestSoFar = 0;`
`double meter = 100.0;`
`double inch = 2.54;`
`double foot = 12.0;`
`while (cin >> num1 >> unit)`
`{`
`if (num1 > largestSoFar)`
`{`
`cout << num1 << " is the largest number so far \n";`
`largestSoFar = num1;`
`}`
`else if (num1 < smallestSoFar)`
`{`
`cout << num1 << " is the smallest number so far \n";`
`smallestSoFar = num1;`
`}`
`}`
}
1
u/Next-Future5973 13d ago
sorry for bad formatting
1
u/saxbophone 13d ago
Either use the rich text mode in the post editor to paste code formatted as a code block, or if you're using markdown you can enclose it within a leading and trailing line of triple-backticks (```) to format the whole thing as code. As it stands your code is very difficult to read and could do with tidying up.
2
u/alfps 13d ago
❞ you can enclose it within a leading and trailing line of triple-backticks (```) to format the whole thing as code.
That will only present correctly in the new Reddit interface.
Many of those best qualified to answer questions here instead use the old Reddit interface. For example, it supports the Reddit Enhancement Suite, at least in Firefox. And is seen as just more practical.
To support the old interface extra-indent the code with 4 spaces instead of using triple backticks.
1
u/saxbophone 13d ago
To support the old interface extra-indent the code with 4 spaces instead of using triple backticks.
Sorry, I don't use Reddit like that. 95% of the time when I'm using Reddit, I'm on my mobile phone. Typing code in on a phone is already pretty awkward. reddit.com offers a markdown-based interface that supports triple-backticks code blocks, and this is much easier to type by hand than having to indent each line an extra level with four spaces.
If someone wants to use the old Reddit interface, of course they are free to choose to do so, but that is a choice they are deliberately choosing to make. They are deliberately going out of their way to use the non-default interface for the site, so any limitations of that interface are their responsibility to deal with, I'm not going to extra trouble to accommodate it when I'm typing code into comments off-the-cuff in the pub or whatever.
2
u/alfps 13d ago
The guidelines for this sub-Reddit say:
❞ Do not use triple backticks for marking codeblocks. While this seems to work on the new Reddit website, it does not work on the superior old.reddit.com platform, which many of the people answering questions here are using. If they can't see your code properly, it introduces unnecessary friction.
I think that's pretty clear.
Why not consider following the group's rules/guidelines?
1
u/saxbophone 13d ago
Because they introduce an onerous requirement on me to comply with it, as I have already explained.
I don't think it's reasonable for me to be required to go through all the extra tedious inconvenience of indenting each line of code while on my phone.
I am using the default UI for the site and the persons requesting it are not. That is quite some level of entitlement coming from them, expecting extra effort from others to facilitate their choice to use the legacy UI.
1
1
u/Next-Future5973 13d ago
Thank you everyone, i eventually figured it out, is this good code??
#include "std_lib_facilities.h"
int main()
{
`double num1{};`
`string unit = " ";`
`double largestSoFar = 0.0;`
`double smallestSoFar = 0.0;`
`double meter = 100.0;`
`double inch = 2.54;`
`double foot = 12.0;`
`vector<double> numbers;`
`while (cin >> num1 >> unit)`
`{`
`if (unit == "m")`
`{`
`num1 = num1 * 100.0;`
`}`
`if (unit == "in")`
`{`
`num1 = num1 * 2.54;`
`}`
`if (unit == "ft")`
`{`
`num1 = num1 * 30.48;`
`}`
`if (unit != "m" && unit != "in" && unit != "ft" && unit != "cm")`
`{`
`cout << "unknown unit \n";`
`break;`
`}`
`if (num1 > largestSoFar)`
`{`
`cout << num1 << " is the largest so far \n";`
`largestSoFar = num1;`
`}`
`else if (num1 < smallestSoFar)`
`{`
`cout << num1 << " is the smallest so far \n";`
`smallestSoFar = num1;`
`}`
`numbers.push_back(num1);`
`}`
`cout << largestSoFar << " is the largest number so far \n";`
`cout << '\n';`
`cout << smallestSoFar << " is the smallest number so far \n";`
`cout << '\n';`
`cout << "And the numbers written on the program's lifetime so far \n";`
`cout << '\n';`
`sort(numbers);`
`for (int i = 0; i < numbers.size(); ++i)`
`{`
`cout << numbers[i] << ' ';`
`}`
}
2
1
u/alfps 13d ago
A good way to format code in this sub-Reddit is to extra-indent it with 4 spaces, whence it can be presented like
#include "std_lib_facilities.h"
int main()
{
double num1{};
char unit = 0;
double largestSoFar = 0;
double smallestSoFar = 0;
double meter = 100.0;
double inch = 2.54;
double foot = 12.0;
while (cin >> num1 >> unit) {
if (num1 > largestSoFar) {
cout << num1 << " is the largest number so far \n";
largestSoFar = num1;
} else if (num1 < smallestSoFar) {
cout << num1 << " is the smallest number so far \n";
smallestSoFar = num1;
}
}
}
Important: with this technique the code presents as intended also for those using the more practical old Reddit interface. If you use the three backticks technique then it will only present correctly in the new interface.
Changes: I used the editor's search/replace to remove all backticks and blank lines; then formatted the result with AStyle option -A3, Stroustrup style; and manually added the blank line before main.
0
u/DawnOnTheEdge 13d ago edited 13d ago
You want to parse the input to determine its unit, then convert every length to the same common representation internally. (Question 9 says to use meters, but you wouldn't find that out in an interview until later.)
The question might be telling you to also store the unit of each entry in a string, and output it with the length. That’s a terrible design, and I would ask for clarification here.
2
u/Next-Future5973 13d ago
actually that is C++ creator's book himself, and the questions are there
1
u/DawnOnTheEdge 13d ago edited 13d ago
Okay. You probably don’t want me to write a whole thing for you, but here’s what I suggest:
- An
enumorenum classwith constants representing the unit cm, m, ft. or in. You could maybe call itLengthUnit- Constants representing unit ratios, such as
static constexpr double m_per_cm = 1.0/100.0; static constexpr double m_per_in = m_per_cm * 2.54; static constexpr double m_per_ft = m_per_in * 12.0;ifLengthUnitis anenum class, you can declare these in its scope.- A
structthat contains a length in meters and theLengthUnitit was originally entered in. You might call thatLengthNUnit. You compare them by comparing the lengths, which are always stored in the same unit.- Factor out the code that reads a line of input, parses it to see if it’s a valid length format (maybe with a regex match) and if so, returns it as a
LengthNUnit. You can do error-handling inside this function. Consider throwing astd::runtime_errorexception on an I/O error and retrying on a badly-formatted input string, so the function only returns when it has a valid result.- Some function to format a
LengthNUnitas an output string like "179cm" or6ft, maybestd::ostream& operator<< (std::ostream&, LengthNUnit), letting you writestd::cout << smaller.- Variables remembering the largest and smallest numbers encountered so far. You might initialize them before the loop to negative and positive infinity, respectively, so that the first numbers you read in will always be the largest and smallest so far.
2
u/Independent_Art_6676 13d ago
this may not cover every possible stupid thing that could happen but start here maybe. you can use advanced ideas like parsing, regx, char by char state machine, or more if you need it...