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.
Related
I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.
#include <iostream>
using namespace std;
int main()
{
int score;
int numTests;
int total = 0; //why total has to be set to 0
double average;
cout << "How many tests: ";
cin >> numTests;
int s = 1;
while (s <= numTests)
{
cout << "Enter score # " << s << ": "; // why put the s there ???
cin >> score;
total += score;
s++; //why update the counter
}
cout << "total" << total << endl;
average = (double)total / numTests;
cout << "Average" << average << endl;
system("pause");
return 0;
}
1.My question is that why does the integer total has to be put as value 0? (int total = 0)
2.on the line that I enter the score number why do I have to input the counter s on it? (cout << "Enter score # " << s <<)
3.and why do I have the update the counter (s++)?
Question 1. in c++ and c when you defined a variable the default of value is anything from memory and its not null or 0
Question 2. cout<< is for print data and when you write cout<
Question 3. s++ mean s=s+1; and this is for the loop end while (s <= numTests)
Before you start counting the scores from the tests, naturally the total number is 0.
You put the counter s to indicate which score should be entered, i.e. "score 1", "score 2", etc... It is there for clarification of the user. Imagine you are on the other side and want to see your average from 20 tests, but each time it just shows: "Enter score:" - first, you will not be sure it works, second, at some point you might become distracted and forget how many scores you have entered. So this shows you exactly where you are at.
s++ means each time the counter increases with 1. So, when it reaches the number of tests, the loop will not continue. The counter is used as a condition for the while loop - so that the cycle will stop and not go inifinitely.
#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.
So as I explained in the title i'm having trouble trying to get the sum of an array. I've just now learned how to create dynamic arrays and I did some searching on how to calculate the sum. I don't believe I fully understand what is going on to calculate the sum.
// Final Grade Calculator
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
double minor, quiz, major;
int minorG, quizG, majorG;
minorG = 0;
cout << "Final Grade Calculator" << endl;
cout << "Input minor grade weight percent." << endl;
cin >>minor;
cout << "Input quiz grade weight percent." << endl;
cin >>quiz;
cout << "Input major grade weight percent." << endl;
cin >>major;
// Three grade categories
minor = minor/100;
quiz = quiz/100;
major = major/100;
for(int i = 1; i <=10; i++){
cout << "Input a minor grade. (Max=10)" << endl;
cin >>minorG;
int *minorGA = new int[minorG];
minorG+= minorGA[minorG];
cout << "Currently: " << i << " Grade(s)." <<endl;
}
cout << "Minor Sum: " << minorG << endl;
return 0;
}
This is what I have so far and the trouble I am having is within the for loop which is where my array is and where I am trying to get the sum of it. When I compile and run I get a sum of 138,427. Any help would be greatly appreciated!
I think you're over-complicating things with dynamic arrays. I'll explain what you're doing, and try to provide help for what I think you're trying to do.
In your code int* minorGA = new int[minorG]; you are allocating memory for minorG amount of ints. There are two problems here:
You are accessing an element outside of the memory you allocated. When you allocate 10 elements, you can access elements 0-9. Trying to access 10 is undefined behaviour (you are trying to access parts of memory that could contain anything).
The values stored in this array are just whatever is in memory, so when you are attempting to increment minorG by the amount of one of these, it's just whatever is in memory at the time.
A separate problem is that you are not deallocating the memory, but some might argue that it isn't really a problem.
You should just be able to have the following to perform what I think you're trying to do:
for (int i = 0; i < 10; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// add that number to some tally:
finalTally += inputtedNumber;
}
Or if you are trying to store the elements in an array, you can use the following:
const int maxElements = 10;
int grades[maxElements] = {}; // this will construct all elements with 0. Without this, the elements may contain any number.
for (int i = 0; i < maxElements; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// Store the number
grades[i] = inputtedNumber;
}
In saying that, it will be better to use std::vector (knows its size, handles memory for you, can grow):
std::vector<int> grades;
// Allow the user to enter as many numbers as they'd like
for (;;)
{
int input = 0;
cout << "Enter a number" endl;
cin >> input;
// Store the number. Will continue to grow
grades.push_back(input);
}
Alright I'll bite, this program does sort the number from highest to lowest but it'll only sort if the numbers are arranged in order from highest to lowest;not if it's sporadic. Here are two example of what I mean.
Example 1: 12,11,10,9,8,7,6,5,4,3,2,1.
Example 2: 32,25,24,31,10,11,15,16,8,19,18,5.
You see how in example 2 that some of the numbers are in order like 32 25 24 but some of the others are not. This is my main problem. My secondary problem is aligning the text vertically so that it looks neat. Should I use setw left, right for this? Please give feedback.
Note 1: The IDE that I'm using is codeblocks.
Note 2: Keep in mind that whatever number the user inputs for a particular month has to be vertically parallel to each.
Note 3: I'm pretty sure the problem is with my selection sort. So you really should be looking at the function void selectionsort since that is the function that is doing all the sorting. I just don't know where I went wrong with my sorting though. Everything else seems to be in order.
/* This program lets the user enter the total rainfall
for each month into an array of doubles. The program also
calculates and displays the total rainfall for a year, the average
monthly rainfall, and the months with the highest and lowest amounts.
The program also displays the list of months, sorted in order of
rainfall from highest to lowest.*/
/* This program does not accept negative numbers for monthly rainfall
figures.*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void SelectionSort(string[], double[], int);// Function Protoype.
int main()
{
const int SIZE = 12; /* A constant integer that represent the total
amount of months in a year. */
double totalRainfallPerMonth[SIZE]; /* Loop this array to force the user
to enter variables for each
element in this array. */
double totalRainfallPerYear = 0; /* The total amount of rainfall
(in inches) per year. */
// An array of every month.
string monthArray[SIZE]={"January", "February", "March", "April", "May",
"June", "July","August", "September",
"October", "November", "December"};
double average; // A variable that holds the average monthly rainfall.
int i; // Will be used as a counter for any loop.
cout << fixed << showpoint << setprecision(2); // Set decimal notation.
for(i=0; i<=11; i++)
{
// Prompt the user to enter values.
cout << "Please enter the total rainfall(in inches) for ";
cout << monthArray[i] << ": ";
cin >> totalRainfallPerMonth[i];
while(totalRainfallPerMonth[i] < 0) /* If the user enters a negative
value */
{
cerr << "No negative values allowed. "; // Display error message.
cout << "Please try again. ";
cin >> totalRainfallPerMonth[i];
}
}
for(i=0; i<=11; i++)
{
// Calculate the total rainfall for a year.
totalRainfallPerYear += totalRainfallPerMonth[i];
}
// Display the total rainfall for a year.
cout << "\nThe total rainfall this year is " << totalRainfallPerYear;
cout << " inches of rain. " << endl;
// Calculate the average monthly rainfall.
average = totalRainfallPerYear / SIZE;
// Display the average
cout << "\nThe average monthly rainfall per month is ";
cout << average;
cout << " inches of rain. " << endl << endl << endl;
cout << "\n" << "Month " << "\t";
cout << " Rainfall(in inches)" << endl;
cout << "-----------------------------------";
SelectionSort(monthArray, totalRainfallPerMonth, SIZE); /* Call in the
function. */
return 0;
}
void SelectionSort(string month[], double rain[], int SIZE)
{
int i;
int j;
int min;
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[j];
rain[j] = tempDouble;
string tempString = month[i];
month[i] = month[j];
month[j] = tempString;
}
}
}
for(i=0; i<=11; i++)
{
/* Display the amount of rainfall per month from highest to
lowest */
cout << "\n" << month[i] << "\t" << rain[i] << endl;
}
}
There is in fact an error in your selection sort implementation: you are swapping elements too early and too often.
Only after you have performed a full sweep over the whole remaining array and therefore have determined the global minimum (I keep that term in order to be consistent with the variable name and the comments in the code, although in fact you are looking for the maximum) you should perform a single swap of the first element of the remaining array with the minimum element.
The corrected code (only the main loop of the sorting function shown) should look like this:
for (i = 0; i < SIZE - 1; i++)
{
min = i; // The intial subscript or the first element.
for (j = i + 1; j < SIZE; j++)
{
if (rain[j] > rain[min]) /* if this element is greater,
then it is the new minimum */
{
min = j;
}
}
// swap both variables at the same times
double tempDouble = rain[i];
rain[i] = rain[min];
rain[min] = tempDouble;
string tempString = month[i];
month[i] = month[min];
month[min] = tempString;
}