Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    forums

Go Back   Code Forums > Application and Web Development > Standard C, C++

Reply
 
LinkBack Thread Tools Display Modes
Old 10-12-2004, 07:53 PM   #16 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
The code follows after this intro.

Look how I also added code to intercept bad input like characters and floating point numbers. So input like j and 2.51 are intercepted. Try it. However, CTRL-Z/D is accepted. /D for *nix systems (bash instead of console).
Also, 2.0 is accepted as well. Since the value is exactly an integer. See if you like it:
Code:
#include <iostream>
#include <string>
#include <limits> //numeric_limits
#include <iomanip> //setprecision etc.
#include <cmath> //modf()

using namespace std;

//Optional function. Depends on IDE. Remove for release version.
void wait_for_enter();

int main()
{
   int num_positives(0), num_negatives(0), num_evens(0), num_odds(0);
   double percent_negatives(0), percent_positives(0), percent_evens(0),
      percent_odds(0);

   //Lets make this double, so no cast is needed later in the %-calculations.
   double total_inputs(0);

   double input; //Trick to check for fractions, wich is also invalid input.
   int theNumber; ///For conversion from double to int.
   while(1)
   {
      //need this bogus variable for modf(). modf() requires it.
      double  intpart;
      cout<<"Please enter an integer (pos or neg). CTRL-Z/D to quit!\n";
      while(!(cin>>input) || modf(input , &intpart) !=0 )
      {
         //CTRL-Z/D entered? If so, then get out of this loop.
         if(cin.eof())
            break;
         cout<<"You didn't enter a number. Try again please."<<endl;
         cin.clear();
         cin.ignore(numeric_limits<streamsize>::max(), '\n');
      }
      //CTRL-Z/D entered? If so, then get out of this loop as well.
      if(cin.eof() )
         break;

      total_inputs++;
      //Lets convert, since we need modulo calculation (can't with type double).
      theNumber = static_cast<int> (input);
      if(theNumber%2 == 0)
         num_evens++;
      else
         num_odds++;
         
      if(theNumber<0)
         num_negatives++;
      else
         num_positives++;
   }
   
   /*CTRL-Z/D is entered, so we end up here. */
   
   cout<<"\t\tTHE RESULTS OF THE ENTRIES"<<endl;
   cout<<"\t\tTotal valid integers: "<<total_inputs<<endl;
   cout<<"\t\tTotal positive numbers: "<<num_positives<<endl;
   cout<<"\t\tTotal negative numbers: "<<num_negatives<<endl;
   cout<<"\t\tTotal even numbers: "<<num_evens<<endl;
   cout<<"\t\tTotal odd numbers: "<<num_odds<<endl;
   
   //Skip if no valid input: avoid dividing by zero and unneeded calculations.
   if(total_inputs > 0)
   {
      //Lets show 10 digit-precision.
      cout<<fixed<<setprecision(10);

      cout<<"\t\tPercent positive numbers: "<<
         num_positives/total_inputs*100<<"%"<<endl;
      cout<<"\t\tPercent negative numbers: "<<
         num_negatives/total_inputs*100<<"%"<<endl;
      cout<<"\t\tPercent even numbers: "<<
         num_evens/total_inputs*100<<"%"<<endl;
      cout<<"\t\tPercent odd numbers: "<<
         num_odds/total_inputs*100<<"%"<<endl;
   }
   else
      cout<<endl<<"\t*** STATISTICS OMITTED: no (valid) integers entered ***"<<endl;

   //Optional. Depends on IDE. Remove for release version.
   wait_for_enter();
   return 0;
}

//Optional. Depends on IDE. Remove for release version.
void wait_for_enter()
{
  cout << "press <enter> to continue...\n";
  // Reset failstate, just in case.
  cin.clear();
  string line;
  getline( cin, line);
}
__________________

Last edited by Valmont; 10-13-2004 at 08:42 AM.
Valmont is offline   Reply With Quote
Old 10-13-2004, 08:43 AM   #17 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
I've changed the code a bit: added more robustness (avoiding division by zero) and added more comments. I also corrected some english (typos). Do you like it this way?
__________________
Valmont is offline   Reply With Quote
Old 10-13-2004, 04:51 PM   #18 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
he likes it this way
Androto is offline   Reply With Quote
Old 10-13-2004, 05:52 PM   #19 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Tell me what grade he got, compared to others in his class. There is some pretty neat stuff in it.
__________________
Valmont is offline   Reply With Quote
Old 10-13-2004, 06:07 PM   #20 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
i'll tell you when he tells me
Androto is offline   Reply With Quote
Old 10-14-2004, 07:30 AM   #21 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
udate...
Quote:
argh. it's still not working. at least the output is being displayed but, my numbers still arent coming out right. let me do a recap on the input output

input - negative or positive integers, ctrl-z to exit input
output -
1. a count of the total numbers entered
-this part is working
2. a percentage of the numbers that were negative
-this is a problem. when entering 3 numbers, 2 of which are negative, the output displays 33.33%. i can't understand why.
3. a sum of the positive even integers
-can't seem to get this one working right. when the sum should be 12, it'll be 16. i've tried a table of values and i am completely at a loss.
4. an average of the positive odd integers
-seems like the compiler is pulling numbers out of it's ass with this one.

anyway, here is my code so far;

Code:
 #include <iostream> 
 using namespace std; 
  
 int main() 
 { 
   int input, rem, evensum = 0, oddsum = 0, negsum = 0, total = 0, possum = 0; 
   double per, avg; 
          
   cout << "Enter an integer or ctrl-z to exit: "; 
   cin >> input; 
          
   while (!cin.fail()) { 
     cin >> input;  //user input 
     //while (input !=0)   ~if i use this instead of if, it just freezes 
     if (input != 0) { 
       total++;  //increment total by 1 
       if (input <= -1) {  //find out negative integers 
         negsum++; //increment negsum by 1 
       }//end of if 
       else { //find out positive integers 
         rem = input % 2; 
         if (rem != 0) {  //find out even integers 
         //if (input % 2 != 0)   ~this doesnt seem to work either 
           possum++; 
           oddsum += input; 
         }//end of if 
         else {  //find out odd integers 
           evensum += input; 
         }//end of else 
       }//end of else 
     }//end of if 
   }//end of while  
          
 per = negsum * 100.0/ total; 
 avg = oddsum * 1.0/ possum; 
          
 cout << "Here is the stats of the " << total << " numbers you entered:" << endl; 
 cout << per << "% of the numbers were negative." << endl; 
 cout << "The sum of the positive even integers is " << evensum << endl; 
 cout << "The average of the positive odd integers is " << avg << endl; 
 }
where is my logic wrong? why am i getting these ghost numbers that appear from nowhere? what really pisses me off is that my nested while isnt working. i'm forced to use an if. too many fricken if's. and the "if (input % 2 = 0) isn't working either. is it just mingw? ofcourse it doesnt help that the textbook that we use is for a c++ app called lookout. and the actual app that we use is mingw. so, sometimes the examples in the book don't exactly work and i'm forced to google things. for example, cin.eof() (from my book) didnt work, but cin.fail() did. i really want to learn this stuff....am feeling a bit discouraged.
Androto is offline   Reply With Quote
Old 10-14-2004, 07:59 AM   #22 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
It's time to teach you from start. We are going to recreate my program above, but this time I'll make sure you know what we are doing. I'll get back soon. I need to prepare some stuff. You'd better be online. You're going to work.
__________________
Valmont is offline   Reply With Quote
Old 10-14-2004, 08:23 AM   #23 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
*** LESSON 1 *** communication

Your code...
Code:
int input, rem, evensum = 0, oddsum = 0, negsum = 0, total = 0, possum = 0; 
   double per, avg;
... doesn't say anything to me. You will need to rename your variables (and functions later and everything else even later) so that a stranger like me does know what you mean.
We start simple:
- We need an input variable. That's one thing that is certain. We want to input integers so it seems. WRONG.
The real requirements are: we want to ACCEPT only integers.
OUR JOB:
Set up some basic code that accepts integers, and integers only.

YOUR JOB (I will do this one for you as an example!):
Make a loop that accepts anything even if wrong input causes errors.

MY SOLUTION:
Code:
#include <iostream>
#include <string>

using namespace std;

//Optional functions: depends on IDE.
void wait_for_enter();

int main()
{
   int input;

   while (1)
   {
      cout << "Enter an integer(CTRL-Z/D to exit) -> ";
      cin >> input;
   }

   wait_for_enter();
   return 0;
}

////////////////////////////////////////////////

void wait_for_enter()
{
  cout << "press <enter> to continue...\n";
  // Reset failstate, just in case.
  cin.clear();
  string line;
  getline( cin, line);
}

////////////////////////////////////////////////
Congratulations, your first assignment is done. We move on now.

YOUR 2nd JOB:
Experiment with it.
- What happens if I enter integers (neg and pos)?
- What happens if I enter "j" instead of integers?
- What happens if I enter CTRL-Z or D for that matter?
- What happens if I Enter 2.5 (fractions)?
- How could I test this? HINT: outcomment the things you don't need, so you'll have some output.

Do it, post asap when done.
__________________
Valmont is offline   Reply With Quote
Reply

Bookmarks

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
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
MAC address iwanttolearnc Platform/API C++ 0 07-27-2004 10:46 PM
install Mono on Mac OS X mcjules MS Technologies ( ASP, VB, C#, .NET ) 2 06-25-2004 10:28 AM
MAC new line? Admin PHP 8 01-13-2004 08:38 PM
mac vs pc ??? sde Lounge 7 10-01-2003 09:09 AM
How about a section on Programming on the Mac. phpjeff Feedback 5 05-08-2002 12:36 PM


All times are GMT -8. The time now is 09:18 AM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.0.0 RC8





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting