Hi I am new to C++ and have been having trouble with this one program. I need to add up different totals calculated in if/while statements from a loop. I am unable to create a formula that works correctly. Any help would be great thanks!
(in my code it is lines 40 and 41 that are causing me difficulty)
(also for the Alumni.txt file that I am attempting to read I am using the following sets of numbers 4000 1
5500 2
33 1
6000 3
516 1
555 2
100 3
6800 3
7000 1
50 2
25 3
75 2
and am successful in everything but summing the total donations and then finding the average)
#include<fstream>
#include<iostream>
#include<cmath>
usingnamespace std;
int main ()
{
double donation_amount, donation_type, donation_total, donation_sum, average;
int counter=0;
ifstream fin;
fin.open("Alumni.txt");
ofstream outfile;
outfile.open("Donations.txt");
if(fin.fail())
{
cout<<"file did not open for reading"<<endl;
system("pause");
return 0;
}
while(fin>>donation_amount>>donation_type)
{
if(donation_type==1)
{donation_total=donation_amount;
cout << "Straight donation of "<< donation_total << " \n";}
elseif(donation_type==2)
{donation_total=donation_amount*2.0;
cout << "Original donation of " << donation_amount <<" matched by NU for total of "<< donation_total << " \n";}
elseif(donation_type==3)
{donation_total=donation_amount*3.0;
cout << "Original donation of "<< donation_amount << "Donation matched by NU and alumni's company for total of "<< donation_total << " \n";}
}
donation_sum=donation_total++;
average=(donation_sum/(2.0));
cout << "the total donations are "<< donation_sum <<" and the average donation is " <<average<< endl;
outfile<<"the total donations are "<<donation_sum<<" and the average donation is " <<average<< endl;
outfile.close();
system("pause");
return 0;
}
Specifically, you want to increment the value of donation_total each time a donation amount is read. You are presently re-assigning the value. Example from line 26 of your code: donation_total=donation_amount;
This makes them equal. To ADD donation_amount to donation_total do this: donation_total += donation_amount;
You will want to start out with donation_total = 0, so initialize it to this where you declare the variable. The above correction should be applied to lines 29 and 32 as well.
Your average calculation looks a bit odd: average=(donation_sum/(2.0));
Shouldn't that be average=donation_total/number_of_donors; ? This pertains to the "number of donations" issue hinted at by hanst99 above. You could increment number_of_donors in your while loop.