Need help using objects and functions -- new to programming - c++

I'm in beginning computer science class and we're currently learning about functions, however I thought that I would take it one step further and start teaching myself about objects early on. I tried to make this Average game score calculator, however upon entering the values 10, 20, 30 and 40 then entering the loop sentinel value of -999. Where I should get an average of 25, as its 100/4, I get 80. I've played around with it quite a bit but just cannot figure out what I'm doing wrong exactly -- I try not to ask for help anymore unless I really can't figure something out after a few hours of reading through google and my books. So any help would be much appreciated :)
EDIT: My question is: Why when I enter all these values do they not go through the proper route and get a correct average? (This is my first time ever even attempting to use objects and don't know very much about how to use them, but I figured trial and error would help me learn.)
Thank you in advanced!
P.S I'm new here, but I hope that I formatted this question correctly as to not get anyone mad at me again. Oh and I know I haven't used the iomanip or string libraries yet, however I plan to in the future so I just left them in there.
//COMSCI 110
//HUNTER DURNFORD
//INPUT
//SPECIAL COMPILER FUNCTIONS
//NONE
//PROCESSING
//
//DATA
//
//LIBRARIES
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;
//PROGRAMMER DEFINED FUNCTIONS
//introduction
//
//Object Classes
//AvgScoreCalculator
//Object class
class AvgScoreCalculator
{
private:
//double total_Scores = game_Scores;// The total scores
//double score_Average = total_Scores / score_Count; // the average equation
public:
double total_Scores; // the total that gets input into the average function
double score_Average; // the average of all the games
double score_Count; // the counter for each individual game entry
double game_Scores; // the scores for the individual games
//char exit_Value;
};//end class
//introduction function
void introduction()
{
cout << "Enter any amount of characters and this program will encrypt them." << endl;
cout << "By Hunter Durnford." << endl;
cout << "Editor(s) used: XCODE TEXT EDITOR and JNotePad 2\n";
cout << "Compiler(s) used: XCODE\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;
}//introduction
//function to get scores from user
double getScoreFunction()
{
double score_Count = 0.0;
double gameScores = 0.0;
double total_Scores = 0.0;
while(true)
{
cout << "What score would you like to input? Or type -999 to exit. ";
cin >> gameScores;
if(gameScores == -999)
{
break;
}
score_Count = score_Count + 1;
gameScores = gameScores + gameScores;
total_Scores = gameScores;
}
return total_Scores;
}//end score function
//Average of all the scores function
double getAverageFunction(double total_Scores, double score_Count)
{
double average_Score;
average_Score = total_Scores / score_Count;
return average_Score;
}
//main program
int main()
{
introduction();
AvgScoreCalculator average_Score; //Declaring the object under the class
//set the integers for the average_score object
average_Score.score_Count = 0.0;
average_Score.game_Scores = 0.0;
average_Score.score_Average = 0.0;
average_Score.total_Scores = 0.0;
average_Score.game_Scores = getScoreFunction();
average_Score.score_Average = getAverageFunction(average_Score.total_Scores, average_Score.score_Count);
cout << "The average of all the game scores is: " << average_Score.game_Scores << endl;
}

(leaving apart problems with the precision of doubles that has been pointed out in the comments)
Problem here:
score_Count = score_Count + 1;
gameScores = gameScores + gameScores;
total_Scores = gameScores;
play it in your head:
gameScores=0.0
total_Scores=0.0
... now you read 10
gameScores=10.0
gameScore=gameScore + gameScore -> 10.0 + 10.0 = 20.0
total_Scores = gameScore = 20.0
... next loop just overwrites.
should be:
score_Count = score_Count + 1;
total_Scores += gameScores;
in addition, score_Count is a local variable of getScoreFunction()... so its changes do not affect the average_Score.score_Count used for the average calculation.

Related

Why a portion of my Array output a value different from what i extracted(c++)? [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 7 months ago.
data11.txt:
Length(l) Time(t) Period(T)
200 10.55 0.527
300 22.72 1.136
400 26.16 1.308
500 28.59 1.429
600 31.16 1.558
ill be taking data from this file above in my code
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <iomanip>
/*Using data11.txt as reference, write code to read from the file. In a pendulum experiment certain data was recorded in order to calculate the acceleration due to gravity. All calculations should be in their SI units
Write a function to calculate the acceleration due to gravity as the slope of the graph to this equation.T=2πlg−−√.
What is the percentage error in your calculated value? Take g=9.8ms-2.
If the pendulum weighs 50g and is displaced at an angle of 30, what will it maximum kinetic energy value for each length of the string? Display your answer in table form. */
using namespace std;
double slope_gravity(double T1, double T2, double L1, double L2){//slope function
double T1_inverse = 1/pow(T1,2);
double T2_inverse = 1/pow(T2,2);
double difference_T = T2_inverse - T1_inverse;
double difference_L = (L2 - L1)/100;
double slope = (difference_T/difference_L);
return slope;
}
const int n = 4;
int main (){
ifstream mydata;
string capture;
float Length[n], Time[n], Period[n], acc_gravity;//declaring variable
mydata.open("Data11.txt");
if (mydata.is_open()){
for (int i=0; i<n+1; i++){
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i];
}
acc_gravity = slope_gravity(Period[1], Period[0], Length[1], Length[0]);//acceleration due to gravity calc
cout << fixed << showpoint << setprecision(1);
cout << "The Acceleration Due To Gravity Obtained Experimentally "
<< "from the data11 file is "<<abs(acc_gravity)<<"ms^-2"<<endl;
cout << "Calculating for Percentage error.............";
cout <<endl<<endl;
float percent_error = (abs(acc_gravity)- 9.8) * 100/9.8;//error analysis
cout << "Percent Error is "<< setprecision(2) << abs(percent_error)<<"%"<<endl;
cout << endl;
cout << "Calculating Max Kinetic Energy of pendulum weighing 50g being "
<< "displaced at an angle of 30\n";
cout << setprecision(4);
float velocity[n], x[n], y;//kinetic energy calc
double max_KE[n];
for (int j=0; j<n+1; j++){
x[j] = 2 * acc_gravity * Length[j]/100;
y = 1 - cos(30);
velocity[j] = sqrt(x[j] * y);
max_KE[j] = 0.5 * 50/1000 * pow(velocity[j],2);
}
cout<<endl<<endl;
cout << setprecision(1);
cout << "Length(m)\tMaximum Kinetic Energy(J)\n";//tabular form display
for (int k=0; k<n+1; k++){
cout << Length[k] <<"\t"<< max_KE[k] <<endl;
}
}
mydata.close();
return 0;
}
The objective of the program is in the first comment above.
At the end of the program, i'm supposed to print the values of length and Maximum Kinetic energy to the console in a tabular form.
However, in the array Length[0], it prints 31.16, but i extracted data from data11.txt, so there is supposed to be the value 200 instead.
The origin of the problem start with this for loop. The for loop works well by extracting values from data11.txt. so the value of Length[0] is 200 here.
i've tried to check why it is behaving this way. The problem starts here;
mydata.open("Data11.txt");
if (mydata.is_open()){
for (int i=0; i<n+1; i++){
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i];
}
But outside the forloop, Length[0] is 31.16. I also noticed that Time[4] has different value from input value which is supposed to be 31.16.
Please any help with this?
What you have noticed is called 'buffer overrun'.
float Length[n], Time[n], Period[n], acc_gravity;
// since 'n' is 4,
// so the valid range of subscript of Length/Time/Period are [0-3]
// That means, if you try to write to Length[4],
// that is invalid, often lead to ruin something else.
mydata.open("data11.txt");
if (!mydata.is_open())
{
fprintf(stderr,"failed to open datafile.\n");
return 1;
}
for (int i=0; i<n+1; i++){ // here the rang of 'i' is [0 - 4]
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i]; // so, when i==4,
// 'buffer overun' happens here.
// 'Time' could be ruined by 'Period'.
}
If you want to skip the 'header' line of input file,
one possible approach is :
"'getline()' once , then enter the loop".
Whatever you choose, just don't 'buffer overrun'.
Good luck.:)

Trouble Implementing Two Vectors MVS C++

Hello Stack Overflow users,
I have this program that i am trying to create for my collection of movies, and please forgive me for some of my mistakes and oversights since I AM NEW TO C++, but basically my program runs (yay) but when I chose any of the four options this error pops up:
Main Error
I want the first program option to display like this:
Akira 10.0
Blade Runner 10.0
Deadpool 8.8
BUT IT DOESN'T DO THAT it just looks like:
10.0
10.0
8.8
Example of my bad output
My output just displays all of the scores on new lines but no movie titles show up and if I try any of the last three options (highest/lowest/average) it just displays the same error: Same error as above
If you could give me any pointers (or a code example) as what I need to do to make the output appear as the bold one above, that would be amazing!
Again please forgive me for possible simple errors I am making since this is my first time working with vectors.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
// Function Prototypes
void displayList(vector<string>,vector<double>);
void highestRating(vector<double>);
void lowestRating(vector<double>);
void averageRating(vector<double>);
// 1st Vector Defintion
vector<string> movies{ // inside this is a list of 48 strings containing movie names (Ex: "Akira", "Blade Runner" };
// 2nd Vector Definition
vector<double> ratings{ // Inside this is a list of 48 doubles that contain movie scores for each movie
and i wish for it to print out directly right of the movie title, then turn to the next line.
Examples of numbers inside this vector: 9.9, 10.0, 5.5, 7.5 };
// Main
int main()
{
cout << fixed << showpoint << setprecision(1);
// Variable Definitions
const int DISPLAY = 1, HIGHEST = 2, LOWEST = 3, AVG = 4;
int response;
cout << "-------Welcome to C++ Newbie's Movie Collection Database-------" << endl;
cout << "\nEnter 1 to display the whole collection" << "\nEnter 2 to display the 5 highest rated movies by me";
cout << "\nEnter 3 to display the lowest 5 rated movies by me" << "\nEnter 4 to display the average score of the movies in the collection along with some other math" << endl;
cin >> response;
// Menu
do
{
switch (response)
{
case(DISPLAY):
{
displayList(movies, ratings);
break;
}
case(HIGHEST):
{
highestRating(ratings);
break;
}
case(LOWEST):
{
lowestRating(ratings);
break;
}
case(AVG):
{
averageRating(ratings);
break;
}
default:
{
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3 || response == 4);
return 0;
}
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val <= movies.size(); ++val)
{
cout << movies[val] << "\t";
for (int rat = 0; rat <= ratings.size(); ++rat)
{
cout << ratings[rat] << endl;
}
}
}
// Display highest by me
void highestRating(vector<double> ratings)
{
double max = ratings[0];
for (int i = 0; i <= ratings.size(); i++)
{
if (ratings[i] >= max)
max = ratings[i];
}
cout << "\nThe highest rated movie is " << max << endl;
}
// Display Lowest by me
void lowestRating(vector<double> ratings)
{
double min = ratings[0];
for (int a = 0; a <= ratings.size(); a++)
{
if (ratings[a] <= min)
min = ratings[a];
}
cout << "\nThe lowest rated movie is" << min << endl;
}
// Average Score by me
void averageRating(vector<double> ratings)
{
double average;
double total = 0;
for (int x = 0; x <= ratings.size(); x++)
{
total += ratings[x];
}
average = total / ratings.size();
cout << "\nThe average is " << average << endl;
double forTheFunOfIt = fmod(average, 2.0);
cout << "\nThe Average divided by 2 is " << forTheFunOfIt << endl;
}
To address your first problem in displayList(), you are displaying a movie, and then looping to display all of the ratings. You probably need to display both within the same single loop. Also, if you do this then you need to make sure that both vectors have the exact same sizes to avoid attempting to access beyond the range of your vector, (it is probably best to use a std::map of movies and rating).
Having said that, for your code above maybe try changing displayList() to something like
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val < movies.size(); val++)
{
cout << movies[val] << "\t" << ratings[val] << std::endl;
}
}
Note, you are not going to want to loop while val <= movies.size(), the indexes to your vector of (for example) 4 movies and 4 ratings will be 0-3, not 0-4. You will encounter an error indicating you are out of range.
Now for your next problem, you are looping in main() on the initial input from the user, but you are never updating the response variable from a user input. This will cause you to fall into an infinite loop! An easy fix for you will be to move cin >> response into the top of your do-while loop.
Moving onto the next couple issues, which is invalid output for your highest, lowest, and average. Again, you should not be looping while the index is less than or equal to the total size of the vector. Instead, you want less than only.
Lastly, you may want to consider passing your vectors as const references

I keep getting 0's when I run my program even though the "user" inputs numbers || c++ painting job

c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.

Getting strange value

I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();

Issue with calling function that takes in three parameters, one being int const [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm posting because I'm having issues figuring out why my "total aid available" is not printing the total of the pell grant, stafford loan, and work-study loan. I've tried fixing my function again and again (I used sources online and in reference book, but I don't know if the issue is that my function won't be called or not, since nothing is printing for the total aid available.
Everything else is fine, except that one thing, and it is really bugging me since no matter what changes I make, I'm in the same state. No errors showing either. I'm using microsoft visual studio for the first time as compiler, so I wonder if that is the issue.
Here is what I have:
#include <iostream>
using namespace std;
double pell_Grant(double); // forward declaration on pell_Grant ( which is a function for calculating pell grant)
double sum(double, int const, double); // declaration for sum function which gives total for the total aid available
int main()
{
double workstudy = 0, pellgrant = 5730, grossincome = 0, Total = 0; // variables
int yes;
int const stafford = 9500; //const declaration
cout << "Lemme Forecast Your FAFSA" << endl;
cout << "Enter your adjusted gross income: " << endl; cin >> grossincome; // input for gross income
if (grossincome >= 30000) // if gross income is higher than 30,000 then print message
{
cout << "Sorry Charlie, your income is too high to run this forecaster!";
return 0;
}
cout << "Can someone claim you as a dependent? [1=yes/0=no]: " << endl; // input to claim dependent or not
cin >> yes;
if (yes == 1) // if 1 for yes is selected then pell grant gets reduced by 750, if 0 or no selected, then program goes by standard procedure
{
pellgrant -= 750;
}
workstudy = 1465; // work study must be nationwide avergae 1,465
if (grossincome >= 19000) // if this condition is met then work study is not met and message is printed as follows...
{
cout << "Your Work-Study Award is not available for your income level" << endl;
workstudy = 0;
}
double foo = pell_Grant(grossincome); // value returned from pell_Grant stored here to give total
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
if (workstudy != 0) // if work study loan isn't more than 19,000 then it will be calculated and printed in next statement
{
cout << "Your Work-Study Award (if available)= " << workstudy << endl;
}
cout << "Your Stafford Loan award (if needed)= " << stafford << endl; // prints stafford loan (const called)
cout << "Your Pell Grant= " << pellgrant << endl; // prints pell grant
cout << "Total Aid Available For You=" << Total << endl; // prints total
return (0);
}
double pell_Grant(double x) // pell_Grant function that calculates pell grant which is assigned 5,730
{
// x is gross income which is assigned 5,730. This is money received that does not need to be repaid.
if ((x > 12000) && (x < 20000)) // statement makes sure adjusted gross is bettween 12000 & 20000
{
double a = x / 1000; // for every 1,000 in adjusted gross income... reduce/subtract 400 from it
a *= 400;
x -= a;
}
if (x > 20000) // check if gross income is more than 20000
{
double a = x / 1000; // for every 1,000 in gross income, subtract 500
a *= 500;
x -= a;
}
return x;
}
double sum(double workstudy , int const stafford, double pellgrant) // function for adding up workstudy loan, stafford loan, and pellgrant loan
{
double Total;
Total = workstudy + stafford + pellgrant;
return (Total); // returns total
}
According to its declaration, the method sum() accepts 3 parameters.
double sum(double, int const, double);
But while calling you are passing only 1 parameter:
Total = sum(workstudy + stafford + pellgrant);
Instead, you need to pass 3 parameters, like this:
Total = sum(workstudy, stafford, pellgrant);
But, I don't understand why you aren't getting any errors! You are trying to call a non-existent function. You must get a compiler error.
You are calling your sum() function incorrectly. This is your code:
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
But your sum() function has three parameters. The correct form to call the function would be:
Total = sum(workstudy, stafford, pellgrant); // sum function is called and stores result in Total