• Log in or sign up for an account here: https://www.sythe.org/login

Help with my very basic C+ code

TheGreatEscape

Active Member
Joined
Feb 4, 2011
Sythe Gold
0
Messages
147
Code:
#include <iostream>
using namespace std;

int main()
{
float count, rollingtotal, number, average;

count = -1;
rollingtotal = 0;


while (number != 00) {
    cout << "Please input a number. Type '00' to exit: ";
    cin >> number;

rollingtotal = (rollingtotal + number);
count++;
}
if (number == 00) {
    average = (rollingtotal / count);
    cout << "The Average of the numbers you entered are: ";
    cout << average;
    cout << " Total numbers entered: ";
    cout << count;
} else {
 cout << "Error";
}
}

2 problems that i have encountered.

1. If a person types '0' the loop will break. How do i make '00' not equal '0'. I know 00 is 0, but is there a way to stop that?

2. My count was always 1 above what it should be, the only way i found to fix this was to delcare count as -1. Is there a better way to fox this problem?

3. How would you write this programe? Since im guessing this could be omptimised alot.

Thanks
 
The problem with integers, you won't be able to exit the loop since any number could be considered as valid input. You can go around it by using a string and detecting if the value is an integer, by using sstream.

Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    cout << "Simple average calculator." << endl;
    cout << "Commands: average(shows average) exit(exit application)\n" << endl;
    
    float total(0),number(0),tick(0),programLoop(0),average(0);
    
    while (1) {
    
          string input;
          string stop;
          cout << "Input: ";
    
          cin >> input;
    
          if (istringstream(input) >> number) {
             total += number;
             tick++;
          }
          else if (input == "average") {
               if (total == 0) {
                         cout << endl << "The average is 0. Good job!\n" << endl;
                         tick = 0,total = 0;
               }
               else {
               average = (total / tick);
               cout << endl << "The average is " << average << ".\n" << endl;
               tick = 0,total = 0;
               }
          }
          else if (input == "exit") {
               return 0;
          }
    
    }
}
 
Runescape Gamblingrunescape gambling
Back
Top