C4700: uninitialized local variable 'tuitionCost' - c++

#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.

Related

I keep getting a variable uninitialized error when calling a function that is asking for user input

#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.

Having trouble passing argument through function

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.

Can someone explain? I got a lucky guess, why does passing this variable by reference, rather than value mess up my program?

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().

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);

Drop lowest input from Array?

I have to find the lowest input given, then average out the total minus the lowest score. I am having a bit of trouble with my averageScore function finding the lowest score from the array. I am getting very odd numbers as my output. Any suggestions on how to adjust this would be appreciated. Thanks in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototypes
double* allocate(int&);
double averageScore(int&);
int main()
{
double* testArray;
int numOfScores;
double average;
testArray = allocate(numOfScores);
average = averageScore(numOfScores);
//delete memory created
delete[] testArray;
return 0;
}
//function to collect user info, dynamically allocate
double* allocate(int &numOfScores)
{
double* testArray;
//prompt user for scores
cout << "How many test scores would\n";
cout << "you like to process: ";
//user input validation
if(!(cin >> numOfScores))
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
else if(numOfScores < 0)
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
//dynammically allocate an arrray to hold the scores
testArray = new double[numOfScores];
//get the scores from user
for (int count = 0; count < numOfScores; count++)
{
cout << "Enter Score: ";
//user input validation
if(!(cin >> testArray[count]))
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
else if(testArray[count] < 0.0)
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
}
return testArray;
}
//function to calculate the average score
double averageScore(int &numOfScores)
{
double* testArray;
double total,
average,
scores[0],
lowest;
lowest = scores[0];
//calculate total scores entered
for(int count = 0; count < numOfScores; count++)
{
total += testArray[count];
//find lowest score entered
for(int count = 1; count < numOfScores; count++)
{
if (testArray[numOfScores] < lowest)
lowest = scores[numOfScores];
}
}
//average the total amount of scores drop the lowest
average = (total - lowest) / numOfScores;
cout << "The average test score is: " << average << endl;
cout << "Lowest is: " << lowest << endl;
return average;
}
std::vector<double> scores = {1.2,6.5,3.0,8.3,4.8,6,7.7};
// drop lowest score
scores.erase(min_element(begin(scores),end(scores)));
double average = accumulate(begin(scores),end(scores),0.0)/scores.size();
Couple issues. You shouldnt have those two for loops nested(instead just check if the value is lower than the lowest using an if statement).
Since this is homework I will give you the steps and then you can fix your code
Loop through and calculate the total, finding the lowest score at the same time
Calculate the average as (total-lowest)/(numScores -1)
Return the average
I think you want to change this line:
if(testArray[numOfScores] < lowest)
to this:
if(testArray[count] < lowest)
Also, as #jzworkman points out, the denominator for averaging should be (numScores - 1) since you are eliminating the lowest score from the numerator. (If applicable, you might want to test for the edge case where there is only one score, which leaves nothing to average once you eliminate the lowest score.)
There are a lot of problems with your averageScore function, but i'll cover the most basic one for now.
First off, you should pass it some sort of data. Right now you're using testArray I don't even see where it is allocated. I'm surprised that you're not getting segmentation faults when you run this.
But it's also not initialized. In c++, when you declare a pointer, the variable it points to has a value. It has a garbage value, and if you perform arithmetic operations with that garbage value, then your output will be garbage too.
You have to make your list of scores available to your averageScore function, preferably by passing them in as a parameter.
the beginning of your averaging function looks like the following:
double averageScore(int &numOfScores)
{
double* testArray;
...
instead it should look like this
double averageScore(double*testArray, int numOfScores)
{
...
when you use &numOfScores instead of numOfScores, that means that if you change numOfScores in your averageScore function, than it will change in your main function as well, and you shouldn't do that.
now, on the double* testArray; line, you're declaring a brand new pointer, named "testArray", and there's no meaningful data in it, although it might be full of garbage. there might be other double pointer variables, named "testArray" in your code, but none of them are in the scope of your averageScore function. If you pass testArray in, in your method call, you'll then be able to use it. for example: double someNumber = testArray[i].
Bare in mind that your array is also being passed by reference. If you would rather pass it by value, you can try
`double averageScore(double testArray[], int numOfScores)`
but don't quote me on that one
Once you've done that, your code will still have some issues, but the output should be meaningful enough that you'll hopefully be able to work those out on your own.