Your itemCnt variable will always be one big than actual number of items, since it will get incremented even when you enter a price that is zero or negative, Also, if you enter something negative as a price, your total price variable will be wrong too. Consider this:
You have entered 10:
totalPrice = 10, itemCnt = 1;
You have entered 20:
totalPrice = 30 itemCnt = 2;
Now you have wanted to quit, and entered -3, since it is not bigger than zero, and now your variables looks like:
totalPrice 27, itemCnt = 3;
at this points, you are out of do-while loop. And that is not what you want, you could define price to be unsigned, and remove 1 from itemCnt to get over this issue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <conio>
int main ()
{
int itemCnt=0;
unsigned double price, totalPrice=0, averagePrice;
cout<<"Program To Calculate The Average and Total Price Of Items \n\n";
do {
cout<<"Enter price of item: ";
cin>>price;
totalPrice += price;
itemCnt++;
} while (price > 0);
--itemCnt; // decrement itemCnt by one
cout<<"\nThe Average Price Of The Items Is "<<totalPrice/itemCnt;
cout<<"\nThe Total Price of the Items Is "<<totalPrice;
cout<<"\nEnd of Program";
getch ();
return 0;
}
|
Since there is no chance that price will be a negative number, you don't have decremented total price problem. And by decremening itemCnt, you will get actual number of items.