/* ************************************************************************** * Program name : 029_Sum_of_GP (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/12 - first version * ************************************************************************** * Description : (a) Input the value of the first item in the GP * * (b) Input the ratio * * (c) Input the number of items in the GP * * (d) Input the no. of decimal digits ti be printed * * (e) Calculation and output result * * (f) Try again * ************************************************************************** */ #include #include #include #include float GPsum(float First, float Ratio, float Items, int Digit) {return (First*(pow(Ratio,Items)-1))/(Ratio-1);} void GPitems(float First, float Ratio, float Items, int Digit) { int Index; for (Index=1; Index<=Items; Index++) { cout << setprecision(Digit) // value prints with 5 decimal digits << setiosflags(ios::fixed |ios::showpoint) << First*(pow(Ratio,Index-1)) << "\t" ; } } // End of function GPitems int main() { // part 1 : declaration int Items, Digit; float First, Ratio; char Again, Showitem; do { // part 2 : Input the basic information do { cout << "\nPlease enter the value of the first item in the GP : "; cin >> First; } while (First<=0); do { cout << "\nPlease enter the ratio : "; cin >> Ratio; } while (Ratio==0); do { cout << "\nPlease enter the number of items in the GP : "; cin >> Items; } while (Items<=0); do { cout << "\nShow all the items in the list (Y/N) : "; cin >> Showitem; } while (Showitem!='Y' && Showitem!='y' && Showitem!='N' && Showitem!='n'); Digit = 2; // Note (1) if (Showitem=='Y' || Showitem=='y') // Note (2) { do { cout << "\nHow many decimal digits should be printed (0-5) ? "; cin >> Digit; } while (Digit<0 || Digit>5 ); } // part 3 : Calculation and output result if (Showitem=='Y' || Showitem=='y') // Note (2) { cout << "\nThe items in the above GP are : \n"; GPitems(First,Ratio,Items,Digit); } cout << "\nThe sum of the above GP is " << setprecision(Digit) // value prints with 5 decimal digits << setiosflags(ios::fixed |ios::showpoint) << GPsum(First,Ratio,Items,Digit) << "\n" << endl; // part 4 : try again ? cout << "\aTry again (Y/N) : "; cin >> Again; cout << "\n"; } while (Again=='Y' || Again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } // End of Main /* Note (1) The default number of decimal digits to be printed is 2. (2) If the user does not want to print the values of all the items in the GP, the computer will not ask the user to input the number of decimal digits to be printed. */