samedi 14 mars 2015

My simple C++ program calculates total payroll amount and I want to know a better and more efficient way to do this


I tried to implement the do..while loop in a simple program. In the program, I ask for a payroll amount, then calculate the sum of the payroll and outputs the sum and the number of valid entries. That's too simple so I decided to add some error checking.



#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;

const int SENTINEL = -1;

int main(){

int payroll, payroll_sum, counter = 0;


do{

cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;

if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}

if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}

}while(payroll != SENTINEL);


cout << "\n\nTotal payroll amount is: " << payroll_sum;

cout << "\nTotal number of entries is: " << counter;


return 0;

}


The code works, but it bugs me that I have to deduct one from the counter and add one to the sum because I don't know how to make the program ignore the SENTINEL input. And, I'm sure that there's a better way to do the error handling. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire