Thread: Help Please with loops displaying a certain value

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    1

    Help Please with loops displaying a certain value

    Okay this assignment is to prompt user for positive integer, compute and display the following: sum, average, and the largest input. It should terminate when a negative value is entered. Okay so I run the program, and it terminates when i plug in a negative number, but it still uses that negative as a value of 1 to add to the sum , and messes up my sum and average. Any help?

    Code:
    // Assignment11Smallest.cpp : Defines the entry point for the console application.
    //
    //terminate if integer is not positive
    #include "stdafx.h"
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main (void)
    {
    int numberofinputs,large,x;
    double sum=0,average;
    numberofinputs=0;
    x=1;
    large=x;
    while (x>=0)
    {
    sum=sum+x;
    numberofinputs=numberofinputs+1;
    cout<<"\n Enter Data"<<endl;
    cout<<"\n Terminate input by entering"<<"a negative number"<<endl;
    cin>>x;
    if (x>large)
    large=x;
    }
    cout<<"number of inputs="<<numberofinputs<<endl;
    cout<<"sum of integers="<<sum<<endl;
    average=(sum)/(numberofinputs);
    cout<<"average="<<average<<endl;
    cout<<"Largest Value="<<large<<endl;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It's not adding in the last one -- it's adding in the first one. You set x to be 1 and add it to your sum before you ask for any input.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loops Trouble
    By rlframpton in forum C Programming
    Replies: 2
    Last Post: 04-17-2009, 01:08 AM
  2. Too many loops D:
    By F5 Tornado in forum C++ Programming
    Replies: 6
    Last Post: 12-03-2007, 01:18 AM
  3. Need Help Displaying A Pattern.
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 10-05-2005, 11:01 AM
  4. For/Next Loops...adding 10 numbers...
    By IanelarAzure in forum C++ Programming
    Replies: 5
    Last Post: 09-12-2002, 12:02 PM
  5. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 04:28 PM