Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jul 17th, 2008, 12:26 AM   #1
Loudnoises
The Loud One
 
Loudnoises's Avatar
 
Join Date: Jun 2008
Location: Alaska
Posts: 6
Rep Power: 0 Loudnoises is on a distinguished road
Wrong output with while loop.

Hello, I am a beginner to C++ and programming all together. I am learning as much C++ as I can before the next school year in which I will be learning Java. I am learning out of a book which I find easily understandable and very beginner friendly. I just finshed Chapter 2 which is on Controll Structures. To sharpen my skills in the subject I decided to embark on a mission of my own and make a program that combines everything learned in that chapter. The program is basically just a grade finder ( hence the name ) it finds averages, ditermines your grade in regard to amount of questions on the test and the amount you got right, and other things that I still need to come up with.

Well, now to the point. I have come across a problem in which I require assistance. I have searched these forums, other forums, and google and still have come up with nothing. The code is meant to gather values untill the EOF is inputted. Then find the average of those grades. The problem I am encountering is when I input something it comes up with something wrong for an average. Example Input: 100, 100, 100 Output: 77

c++ Syntax (Toggle Plain Text)
  1.  
  2.  
  3. cout << "\n";
  4. cout << "You chose option 2. Enter the grades. When you are finished entering grades press (ctl + z).\n\n";
  5.  
  6. while ( ( gradeavg = cin.get() ) != EOF ) {
  7.  
  8. cout << "Please enter a grade.\n";
  9. cin >> gradeavg;
  10. cout << "\n";
  11. gradecount = gradecount + 1;
  12. total = total + gradeavg ;
  13. };
  14.  
  15. average = total / gradecount;
  16. cout << "The average is " << average << endl;

The variables are declared as:

c++ Syntax (Toggle Plain Text)
  1. int gradeavg = 0;
  2. int total = 0;
  3. int average = 0;
  4. int gradecount = 0;

Knowing myself, it is probably something right in front of my nose that is so simple. I've must have read over it 100 times and I still can't figure out the problem.

Another example: Input = 100; Average = 55...
Help is greatly appreciated. Thanks.

One question. Does the EOF key actually represent a value. The book said that its a replacement for the sentinal value, but does it have an actual numerical value ( i.e -1)?
Loudnoises is offline   Reply With Quote
Old Jul 17th, 2008, 1:39 AM   #2
casesensitive
Programmer
 
Join Date: Oct 2007
Posts: 32
Rep Power: 0 casesensitive is on a distinguished road
Re: Wrong output with while loop.

Its the way you do the count. Even after you end the program it adds one more to count. So when you input three numbers it runs the loop again to do the exit command. it still adds one more to count A simple fix would be "average = total / (gradecount-1);"
casesensitive is offline   Reply With Quote
Old Jul 17th, 2008, 3:25 AM   #3
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,207
Rep Power: 5 grumpy is on a distinguished road
Re: Wrong output with while loop.

The simpler fix would be to terminate the loop if any of the operations (cin.get() or cin << gradeavg) encounter an error.
grumpy is offline   Reply With Quote
Old Jul 17th, 2008, 9:33 AM   #4
rhish.franks
Programmer
 
Join Date: Feb 2008
Location: India
Posts: 58
Rep Power: 1 rhish.franks is on a distinguished road
Re: Wrong output with while loop.

u can use IF conditioning for incrementing the counter!
rhish.franks is offline   Reply With Quote
Old Jul 17th, 2008, 11:04 AM   #5
Loudnoises
The Loud One
 
Loudnoises's Avatar
 
Join Date: Jun 2008
Location: Alaska
Posts: 6
Rep Power: 0 Loudnoises is on a distinguished road
Re: Wrong output with while loop.

Yep, those worked. Thanks for the replies.
Loudnoises is offline   Reply With Quote
Old Jul 17th, 2008, 12:04 PM   #6
rhish.franks
Programmer
 
Join Date: Feb 2008
Location: India
Posts: 58
Rep Power: 1 rhish.franks is on a distinguished road
Re: Wrong output with while loop.

you are welcom
rhish.franks is offline   Reply With Quote
Old Jul 17th, 2008, 4:28 PM   #7
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,009
Rep Power: 5 lectricpharaoh will become famous soon enough
Re: Wrong output with while loop.

Glad to see you've solved your initial problem, but I have a piece of advice: check the user input for validity before using it. Even if you tell your users to enter a number, you'll get some idiot who will enter 'hello!' at the prompt, causing your program to die a nasty death. If you make plans to account for this situation before it happens, life will be much easier for you.

If you've covered writing your own functions, this sort of thing is a prime candidate. You can write a function to display a prompt and read a number from the console (well, technically 'standard input', which defaults to the console), and re-query the user if the input is bad. You can also use this to do range-checking on the values, so that out-of-range values (for example, as I assume your grades are percentages, it's unlikely you want to allow one higher than 100 or less than zero) will also cause a re-prompt.

The following code should be a good example to show what I mean:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. // our function prototype, so the code compiles. :)
  6. bool readNumber(std::istream &inp, std::ostream &outp, char *prompt,
  7. char *errorPrompt, int &value);
  8.  
  9.  
  10. int main(int argc, char* argv[])
  11. {
  12. int x;
  13.  
  14. if(readNumber(std::cin, std::cout, "Enter a number: ",
  15. "Error! Enter a number: ", x))
  16. std::cout << "You entered the number '" << x << "'.\n"
  17. << std::endl;
  18. else
  19. std::cout << "You hit the end of file.";
  20. return 0;
  21. }
  22.  
  23.  
  24. // our actual function. 'inp' is the input stream, where you can pass
  25. // 'std::cin' or a file that you've opened for reading. 'outp' is the
  26. // output stream, where you can pass 'std::cout' or a file you've
  27. // opened for output. 'prompt' is the initial prompt to display to
  28. // the user, while 'errorPrompt' is displayed on subsequent tries if
  29. // the user gets it wrong the first time. 'value' is the value to be
  30. // set. the return value is 'true' if it successfully read a number
  31. // from the user, and 'false' if it could not, because an end-of-file
  32. // condition occurred. you can simulate an EOF condition at the
  33. // console by entering a key combination, generally with ctrl-D or
  34. // ctrl-Z (it depends on your system) followed by ENTER.
  35. bool readNumber(std::istream &inp, std::ostream &outp, char *prompt,
  36. char *errorPrompt, int &value)
  37. {
  38. outp << prompt; // display prompt
  39. inp >> value; // get input
  40. while(!inp.eof() && !inp.good()) // make sure it's good input
  41. { // the input is bad, so we...
  42. inp.clear(); // clear the error on the stream,
  43. // so we can make another attempt
  44. inp.sync(); // synchronize the stream with the
  45. // underlying buffer, so we won't
  46. // just read the offending input
  47. // a second time,
  48. outp << errorPrompt; // output the 'idiot prompt',
  49. inp >> value; // and try again
  50. }
  51. return inp.eof() ? false : true; // and we're done
  52. }
There you go. Now when you need to read input, you can just call this function, and if it returns true, you know it completed successfully. Adding the range-checking should be a pretty trivial step, and I leave this as an exercise for you.

As a final note, if you're confused by the syntax of the return statement in the function, don't be. The conditional operator, also referred to as the ternary operator ('ternary' being three, much as 'binary' is two, because it takes three operands), is a sort of shorthand for an if-then-else construct.

Basically, when you have a statement of the form A ? B : C, it first evaluates the expression A. If this evaluates to true (or any nonzero value), the value of the entire ternary expression is B. Otherwise, it is C. This is a handy thing to use in assignments and return statements, but you can't use it to conditionally call arbitrary functions as you can with a 'proper' if()..else() statement. The expression A can be a function call, but it needs to be one that returns a value the compiler can consider as a true/false one (ie, a bool or some form of integer), and the expressions B and C need to return compatible non-void types.

Incidentally, I could have just used return !inp.eof(); instead (in fact, this would be more efficient and easier to read), but I wanted to introduce the conditional operator, because it's so much fun. Now you can impress your classmates, and it works in Java too (though there, the expression A must be type boolean, and not an integer).

[edit] Forgive the fucked-up formatting. It looked fine when I did the 'preview post', but then the forum chewed it up and regurgitated it, and I'm too lazy to try to fix it. It's only cosmetic, after all. If you want to cut-and-paste it, just use the 'toggle plain text' linkie. [/edit]
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick

Last edited by lectricpharaoh; Jul 17th, 2008 at 4:55 PM.
lectricpharaoh is offline   Reply With Quote
Old Jul 17th, 2008, 9:15 PM   #8
Loudnoises
The Loud One
 
Loudnoises's Avatar
 
Join Date: Jun 2008
Location: Alaska
Posts: 6
Rep Power: 0 Loudnoises is on a distinguished road
Re: Wrong output with while loop.

I have to thank you alot for that man. I really appreciate such a detailed reply. The next chapter in the book is on Functions, and this will give me a head start. I decided to make the program again after the end of this chapter; accept use functions as you did above.

I thank you guys again for your replies, and I hope I can contribute back as my skills increase in the subject.

Quote:
Even if you tell your users to enter a number, you'll get some idiot who will enter 'hello!' at the prompt.
So true.
Loudnoises is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
What is wrong with this Output Statement kewlgeye Visual Basic 2 Jan 25th, 2008 10:46 PM
Array with For Loop namsu Java 9 Jan 3rd, 2008 5:56 PM
Change the name of output file jazz C 4 Jun 28th, 2006 2:54 AM
It's giving me "Press any key to continue" and no other output.. Insomniac C 15 Jun 5th, 2005 7:07 AM
Timing loop problems badbasser98 C++ 11 Mar 10th, 2005 8:30 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 5:09 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC