Having trouble with the function call for monthlyAverage() function because I do not know what to pass through in order for it to work.
// Zachary Fernandez
// Term Project Part II
// TP21_rainfall_statisitcs.cpp
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void userInput(double rainfall[]);
double totalRainfall(double rainfall[]);
double monthlyAverage(double sum);
int main()
{
double rainfall[12];
cout << "Please enter the rainfall of each month of the year\n";
cout << "seperated by a space.\n";
userInput(rainfall);
totalRainfall(rainfall);
monthlyAverage();
system("pause");
return 0;
}
void userInput(double rainfall[])
{
for (int i = 0; i < 12; i++)
{
cin >> rainfall[i];
}
}
double totalRainfall(double rainfall[])
{
double sum = 0;
for (int i = 0; i < 12; i++)
{
sum += rainfall[i];
}
cout << "The total amount of rainfall for the year is: ";
cout << sum;
cout << endl;
return sum;
}
Having trouble with this function because the function call is not allowing me to pass anything through. I also do not know what to pass through in order for it to work.
double monthlyAverage(double sum)
{
double average;
average = (sum / 12);
cout << "The average monthly rain fall is: ";
cout << average;
cout << endl;
return average;
}
I think you would need something like this:
int main()
{
double rainfall[12];
cout << "Please enter the rainfall of each month of the year\n";
cout << "seperated by a space.\n";
userInput(rainfall);
double total = totalRainfall(rainfall);
double avg = monthlyAverage(total);
cout << "Monthly Average:" << avg << endl;
system("pause");
return 0;
}
Well you declared it to take in a double, so any double value will work. I am assuming sum means total rainfall, so you can either store the value of the totalRainfall() function in a variable, then pass the variable, or do something like
int average = monthlyAverage(totalRainfall(rainfall));
This will use the value returned by the totalRainfall function and pass it into monthlyAverage, then store the result into int average.
Since your totalRainfall method prototype is - double totalRainfall(double rainfall[]), it means the function is returning a double value which you can pass to monthlyAverage function.
double total = totalRainfall(rainfall);
double avg = monthlyAverage(total);
You can store the return value in a variable (avg in the example) as shown above.
This function takes one double Argument
double monthlyAverage(double sum);
So you must pass a double value in order to work.Like
monthlyAverage(100.5);
In your case it is look like this
monthlyAverage(totalRainfall(rainfall));
Looking at your context, this exercise (?) seem to suggest that you write
monthlyAverage(totalRainfall(rainfall));
Why? you see that totalRainfall returns a double, and it passes to monthlyAverage to output the average.
By the way, your system("pause"); is not very portable.
Say, Apple version is different.
Related
I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double tuitionCalc(int sumCreditHoursTaken); //function prototype
double tuitionCost;
double creditHours;
int numCourses;
int count;
int sumCreditHoursTaken = 0;
cout << " This program calculates a students total number of\n\n";
cout << " credit hours and tuition for a given semester.\n\n\n";
cout << "Please enter the amount of courses you will be taking this semester: ";
cin >> numCourses;
for (count = 1; count <= numCourses; count++) //for loop to find the total credit hours taken
{
cout << "\nPlease enter the number of credit hours for class " << count << ": ";
cin >> creditHours;
sumCreditHoursTaken += creditHours;
}
cout << "\n\nYour total number of credit hours taken is: " << sumCreditHoursTaken << "\n\n";
cout << "Your total tuition will be: $" << tuitionCalc(tuitionCost) << "\n\n";
system("PAUSE");
return 0;
}
It says the problem is occurring above where i try to call the function tuitionCalc().
Here's the function I'm trying to call:
double tuitionCalc(int sumCreditHoursTaken)
{
double tuitionCost = 0;
double costCreditHour = 147.00;
double maintFeeAddOn = 29.33;
int maxHoursFullTuition = 12;
if (sumCreditHoursTaken <= maxHoursFullTuition)
sumCreditHoursTaken * costCreditHour;
else
(maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
}
In the line
cout << "Your total tuition will be: $" << tuitionCalc(tuitionCost) << "\n\n";
you use the function tuitionCalc with an uninitialized argument tuitionCost. So the compiler tries to warn you. This is technically undefined behaviour. You need to make sure that whatever you pass to your function has a well defined value. In your case, because tuitionCost is not initialized, you pass whatever junk value happens to be stored at the memory location &tuitionCost. Remember that C++ does not initialize variables to zero for you. You need to initialize them manually if you pass them by value to a function. My guess is that you actually want to pass sumCreditHoursTaken (which you just compute above the function invocation) to your tuitionCalc function.
You are passing the value of tuitionCost to the tuitionCalc method but you have not put anything in tuitionCost. Since the variable is declared locally it will have a random value in it. The compiler wants you to know that.
Whenever I change the function "double getsales (double &num)" to double getsales (double num) and the function prototype appropriately, the program doesn't correctly. I don't understand why my lucky guess fixed it, no matter how much I try to read about reference variables.
Can someone explain?
#include <iostream>
#include <iomanip>
using namespace std;
double getsales (double &);
void findhighest (double, double, double, double);
int main()
{
double northeast = 0;
double southeast = 0;
double northwest = 0;
double southwest = 0;
cout << "Enter NorthEast sales: $" ;
cout << getsales(northeast) << endl;
cout << "Enter SouthEast sales: $";
cout << getsales(southeast) << endl;
cout << "Enter NorthWest sales: $";
cout << getsales(northwest) << endl;
cout << "Enter SouthWest sales: $";
cout << getsales(southwest) << endl;
findhighest(northeast, southeast, northwest, southwest);
return 0;
}
double getsales (double &num)
{
do
{
if(!cin)
{
cin.clear();
cin.ignore(100, '\n');
}
cin >> num;
cout << "Number entered: ";
}while(!cin || num <= 0);
return num;
}
void findhighest (double ne, double se, double nw, double sw)
{
const char *who = "NorthEast";
double high = ne;
if(se > high)
{
who = "SouthEast";
high = se;
}
if(nw > high)
{
who = "NorthWest";
high = nw;
}
if(sw > high)
{
who = "SouthWest";
high = sw;
}
cout << fixed << showpoint << setprecision(2) << endl;
cout << who << "has the highest sale ($" << high << ")" << endl;
}
When passing by value, getsales won't modify the original number passed as parameter.
Therefore, the call
findhighest(northeast, southeast, northwest, southwest);
will operate with the original numbers (which are zero).
You should use the modified values.
with
double getsales(double&num);
double southwest = 0;
cout << getscales(southwest);
your function getsales() actually works on the variable handed in by the caller (using num as local name for it), i.e. it reads directly into the variable southwest of the calling program. It also returns that value, but that will not change the variable southwest.
When instead you have
double getsales(double num);
the function works with its own internal variable num, which is initialised to the value passed by the caller, i.e. with 0 since that's the value of southwest at the moment of call. It thus has no effect on the variable southwest. The function does return the same value, though.
Thus in the first case (using references), the variables southwest etc. are modified but not in the other case of your program.
However, returning a value via a reference is not necessarily best practice, because it is not evident from the function call (i.e. without having seen the function declaration) that this will potentially modify the variable passed. Instead, a 'getter' typically returns the value, i.e. has prototype
double getsales();
then the usage could be
cout << (southwest = getsales()) << endl;
etc. In this case, it is selfevident what's going on, even without having seen the prototype for getsales().
I'm pretty new to C++, only had experience in C#, Python, and JS so bear with me!
I am taking the user's input on 5 scores and storing it in an array. I pass the array off and evaluate the scores in the array to find the lowest value and highest value. I need to drop those two, then find the average of the other 3 values. My problem is, I'm not finding the highest/lowest value. I have the logic in findLowest() and findHighest() but to test it I put the same logic in main() to see if its working before its passed off, and its not working. Can someone guide me to finding the highest/lowest values in the array? Thanks!
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;
void getJudgeData(double score)
{
cin >> score;
if (score > 10 || score < 0)
{
cout << "Invalid score, please enter again." << endl;
cin >> score;
}
else
{
cout << "Thank you." << endl;
}
}
double findLowest(double scores[])
{
double lowScore = *min_element(scores, scores+5);
return lowScore;
}
double findHighest(double scores[])
{
double highScore = *max_element(scores, scores+5);
return highScore;
}
double calcScore(double scores[])
{
double finalScore;
double sum = 0;
double newScore[3] = {};
double lowScore = findLowest(scores);
double highScore = findHighest(scores);
int j = 0;
for (int i=0; i < 5; i++)
{
if (scores[i] != lowScore && scores[i] != highScore)
{
scores[i] = newScore[j];
j++;
}
}
for (int k=0; k < 3; k++)
{
sum = sum + newScore[k];
}
finalScore = sum/3;
return finalScore;
}
int main()
{
double finalScore;
double judgeScores[5] = {};
for (int i = 0; i < 5; ++i)
{
cout << "Enter judge " << i + 1 << "'s score: ";
getJudgeData(judgeScores[i]);
}
finalScore = calcScore(judgeScores);
cout << "Highest score is: " << *max_element(judgeScores, judgeScores+5) << endl;
cout << "The final score is: " << finalScore << endl;
// This prevents the Console Window from closing during debug mode
cin.ignore(cin.rdbuf()->in_avail());
cout << "\nPress only the 'Enter' key to exit program: ";
cin.get();
return 0;
}
This is because getJudgeData takes double score by value. As the result, the entries by the end user remain confined to the getJudgeData function; the judgeScores[i] variable that you pass to the function remains unchanged.
Add an ampersand to fix this problem:
void getJudgeData(double &score) {
...
}
Now the parameter is passed by reference, letting getJudgeData make modifications to it.
Change
void getJudgeData(double score)
to
void getJudgeData(double &score)
It looks like most of your logic is OK, except you have your assignment swapped in calcScore(). You have:
scores[i] = newScore[j];
You probably meant:
newScore[j] = scores[i];
Also, be wary: If your input array contains multiple scores equal to the minimum or maximum, you will have less than 3 remaining after you remove them.
Edit: Oh yeah, and also what others have said about passing the value by reference to getJudgeData().