The
value
variables declared at lines 28 and 69 are different variables. So when you check
value
at line 37, you're checking the uninitialized value declared at line 28. To fix this, just change line 35 to:
value = myPrompt();
You have a similar problem with the total variable. Change line 42 to
total = mySum(value);
If the user doesn't enter the sentinel, then the loop at line 37 will continue forever. I would change lines 35-37 to:
1 2 3 4 5
|
while (true) {
value = myPrompt();
if (value == SENTINEL) {
break;
}
|
In mySum() and myProd(), you need to initialize total to something. Be careful here: the right initial value is not the same in the two functions.
The logic at line 40 is wrong. Every number is either greater than 10
or
less than 50.
I would get rid of myPrint() completely and just print the appropriate strings where you currently call myPrint(). It does something different at each call site anyway so there is no code savings by making it a function.
I respectfully disagree with some of
admkrk's comments:
A function that is only called once serves no purpose. |
It makes the code easier to read, write and maintain, which are all major reasons for any high level language.
you give it a void argument, which is another useless thing. |
I'm not sure if he's objecting to the declaraion (
int myPrompt(void)
vs
int myPrompt()
) or the fact that it takes no arguments. I think it's fine to have functions that take no arguments but I agree that they should be declared as
func()
instead of
func(void)
.
You also give it a return value of an integer, which is also meaningless, as your code is written. |
The problem isn't the return value, the problem is that you were ignoring it.
You set const int SENTINEL = -9999; , then ask for a positive number. |
The prompt is
cout << "Enter a non-negative integer (-9999 to end):";
This seems crystal clear to me.
The logic of [myPrompt()] is completely wrong |
I would code it differently, but other than the unnecessary
value = SENTINEL
at line 79, the logic is fine.
If they enter a positive value, as would be expected, your while loop will never be entered, |
That's the point. If they enter a positive number then myPrompt() returns it.
and the only way to get out of the while loop is to enter -9999 or a positive number. |
That's the point of the while loop.