My average function is dropping the last element.
I tested it using the numbers 0, 5, 10, 20 in which I get an average of 5.00 instead of 8.75.
If you switch the numbers around, the last element still gets dropped.
Also, there's another problem that happened when my teacher tried to run it, but one I've been unable to replicate which is some weird large number getting thrown in the first element after being sorted.
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
using namespace std;
int getNumber();
void getMovieData(int *, int);
void sort(int *, int);
double getAverage(int *, int);
void print(int *, int);
int main()
{
int students, i, j;
int *movies;
cout << "Enter the number of Students surveyed: ";
i = getNumber();
movies = new int[i];
getMovieData(movies, i);
cout << endl << "--- Here is the data you entered ---" << endl;
print(movies, i);
cout << endl << "--- Here is the data after being sorted --" << endl;
sort(movies, i);
double average = getAverage(movies, i);
print(movies, i);
cout << endl << "The average number of movies seen is " << fixed
<< showpoint << setprecision(2) << average << endl; //rounding to
system("PAUSE");
return 0;
}
// Function used to input positive number
int getNumber()
{
int number;
cin >> number;
// Validation
while (number < 0)
{
cout << endl << "Number cannot be negative: "
"Please enter a nonnegative value: ";
cin >> number;
}
return (number);
}
// Function to input values into the array, movies of size SIZE
void getMovieData(int *ptrToArray, int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << endl << "Enter the number of movies Student " << i+1 << " saw: ";
ptrToArray[i]= getNumber();
}
}
// Bubble Sort the Data
void sort( int *ptrToArray, int SIZE)
{
for (int j = 0; j < SIZE; j++)
{
for (int i = 0; i < SIZE; i++)
{
if (ptrToArray[i] < ptrToArray[i+1])
{
int temp = ptrToArray[i];
ptrToArray[i] = ptrToArray[i+1];
ptrToArray[i+1] = temp;
}
}
}
}
// Simple Average function; returns average to average in main
double getAverage(int *ptrToArray, int SIZE)
{
double total=0;
for(int i=0; i < (SIZE); i++)
{
total += ptrToArray[i];
}
double average = total/(SIZE -1);
return (average);
}
//A function to print the arrays only! the average is printed in main
void print(int *ptrToArray, int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << ptrToArray[i] << setw(10);
}
}
The numbers to input are this:
4
0
5
10
20
with an output of 20, 10, 5, 0 and average of 5.00
and the second set of numbers is:
4
4
22
3
55
with an output of 225982769 55 22 4 (sorted) and average of 32283264.29
With the second set of numbers, I was unable to replicate the output she got as I got the correct sort, but obviously the wrong average. Any help you can give me is much appreciated.
EDIT: There was an issue with the compiler not including the file I was working with in the Project and instead, using the old one. The only difference was
total/7
versus
total/SIZE
which is why the average was off. It SEEMED like it was dropping the last element but it really just so happened to be a coincidence that they totaled 35 and divided by 7 is 5.00 which is also the average if you dropped the 20.
Once I changed the right .cpp file, it worked perfectly (pretty much all the changes you guys suggested had been the original code, and were changes I made to try and alter the average, which didn't change because I wasn't altering the right source file. In short, problem solved.)
You need to include the last element in you averaging function. Either do
for(int i = 0; i < SIZE; ++i)
or
for(int i = 0; i <= (SIZE - 1); ++i)
You have an off-by-one error
for(int i=0; i < (SIZE - 1); i++)
You need i < SIZE. Same goes for the division,
double average = total/(SIZE -1);
Here you need SIZE, not SIZE-1 too.
Also,
system("PAUSE");
Should be avoided. It's better to use something like getchar().
Related
`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|
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 6 years ago.
Improve this question
Hi i'm trying to Write a program in C++ to, generate and print 20 random numbers, between 0 to 999, and do the following operations without using inbuilt functions, find and print the: min value, max value, average, median, standard deviation, variance. Do a binary search on the 15th element. Please help me with the code.
So far i've done this much
#include
#include
#include
using namespace std;
void minimum(int[], int);
void maximum (int[], int);
void average(int[], int);
void median(int[], int);
void mean(int[], int);
void sort(int[], int);
int ra()
{
int r = rand() % 1000;
return r;
}
int main ()
{
srand(time(NULL));
ra();
int array[20];
int num=20;
for (unsigned int i = 0; i < num; i++)
{
array[i] = ra();
cout << "Index: " << i << ", random number: " << array[i] << endl;
}
minimum();
new_array[20];
num=20;
for (unsigned int i = 0; i < num; i++)
{
new_array[i] = new_array();
cout << "Index: " << i << ", random number: " << minimum << endl;
}
return 0;
}
void minimum(int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] minimum)
minimum = new_array[i];
cout << "Maximum value: " << minimum << endl;
}
void maximum (int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] > maximum)
maximum = new_array[i];
cout << "Maximum value: " << maximum << endl;
return 0;
}
void median(int new_array[], int num)
{
//CALCULATE THE MEDIAN (middle number)
if(num % 2 != 0){// is the # of elements odd?
int temp = ((num+1)/2)-1;
cout << "The median is " << new_array[temp] << endl;
}
else{// then it's even! :)
cout << "The median is "<< new_array[(num/2)-1]<<new_array[num/2]< endl;
}
mean(new_array, num);
}
void sort(int new_array[], int num)
{
//ARRANGE VALUES
for(int x=0; x<num; x++){
for(int y=0; y<num-1; y++){
if(new_array[y]>new_array[y+1]){
int temp = new_array[y+1];
new_array[y+1] = new_array[y];
new_array[y] = temp;
}
}
}
cout << "List: ";
for(int i =0; i<num; i++){
cout << new_array[i] << " ";
}
cout << "\n";
median(new_array, num);
}
void average_(int new_array[], int nums)
{
float sum;
for (unsigned int i = 0; i < 20; ++i)
{
sum+=num;
}
cout << "Average value: " << average_/num << endl;
}
Please tell the necessary corrections
You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don't know what you mean by "Do a binary search on the 15th element"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int ra()
{
// You wanted a number between 0 and 999 inclusive so do not add 1
// Instead do a modulus of 1000
int r = rand() % 1000;
return r;
}
int main ()
{
// Do this to get different random numbers each time you run your program
srand(time(NULL));
// You have to call ra as a function. Do this by writing: ra()
// Here I am storing 20 random numbers in an array
int nums[20];
for (unsigned int i = 0; i < 20; ++i)
{
nums[i] = ra();
cout << "Index: " << i << ", random number: " << nums[i] << endl;
}
// Iterate to find the minimum number
int minimum = nums[0];
for (unsigned int i = 1; i < 20; ++i)
if (nums[i] < minimum)
minimum = nums[i];
cout << "Minimum value: " << minimum << endl;
// TODO: Find the maximum in basically the same way
// TODO: Find the average by summing all numbers then dividing by 20
// TODO: Find the median by sorting nums and taking the average of the two center elements
// TODO: etc.
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int r;
int ra;
int i=0;
int ra(){
r = (rand() % 999) + 1;
return r;
}
int main ()
{
int random_;
srand((int)time(0));
while (i++ < 20)
{
random_ = r;
cout<< random_<<endl;
}
return 0;
}
I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}
I am trying to understand sorting algorithms, so based on googled examples/explanations I wrote the below code. Code works 80% of the time. Every once in a while it doesn't sort properly and I can not see why.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void setArray( int *, const int & );
void selectionSorting( int *, const int & );
int main()
{
int numOfElem;
cout << "Num of array elements: ";
cin >> numOfElem;
cout << '\n';
int array[numOfElem];
setArray(array, numOfElem);
selectionSorting(array, numOfElem);
cout << '\n';
return 0;
}
void setArray( int *array, const int & numOfElem ){
srand(time(0));
cout << "Original array: " << '\n';
for (int i=0; i<numOfElem; i++){
array[i] = rand()%30;
cout << array[i] << ' ';
}
cout << '\n';
}
void selectionSorting( int *array, const int &numOfElem ){
int eff_size, swap;
int maxpos = 0;
for (eff_size = numOfElem; eff_size>1; eff_size--){
// loop searching for a position of largest number in the array
for (int i=0; i<eff_size; i++){
maxpos = array[i] > array[maxpos] ? i : maxpos;
}
swap = array[maxpos];
array[maxpos] = array[eff_size-1];
array[eff_size-1] = swap;
}
cout << "Selection Sorting: " << '\n';
for (int i=0; i<numOfElem; i++){
cout << array[i] << ' ';
}
}
Example output:
Num of array elements: 5
Original array:
7 17 1 12 25
Selection Sorting:
1 7 17 25 12
I can't see any pattern to the sorting failing - it fails in different places, weather there are repeated numbers, regardless of how many numbers I provide etc...
On each iteration of the outer loop(over eff_size) you should re-set maxpos to 0. Otherwise you have the chance that maxpos goes out of the effective portion being sorted(this happens if the maximum element is last in the effective portion i.e. if maxpos==effsize).
I am a bit stuck with my program, The program is to Read in a set of results and then construct a histogram that indicates how many marks are in each decade i.e how many between 10-20 etc.
I have 2 problems
How can I edit my code to only allow the readExamResults to store ones in the range of 0 -100
How can I get the PrintHisto to print the * at a certain setw() dependant on which decade each of the results where in. e.g. If I entered 3,4,5,11,23 It should show 3 * in the <10 decade, 1 in the 10-20 decade and 1 in the 20-30 decade.
any help will be much appreciated.
code:
using namespace std;
void readExamMarks(int examMarks[], int sizeOfArray){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
examMarks[idx] = x;
}
}
void printExamMarks(int examMarks[], int sizeOfArray){
for(int x = 0; x < sizeOfArray; x++){
cout << setw(5) << examMarks[x];
}
cout << endl;
}
void printHisto(int examMarks[], int sizeOfArray){
system("cls");
for( int x = 0; x < 6; x++){
cout << setw(5) << "*" << endl;
}
}
int main()
{
int examMarks[5];
readExamMarks(examMarks, 5);
printHisto(examMarks, 5);
printExamMarks(examMarks,5);
system("PAUSE");
}
How can I edit my code to only allow the readExamResults to store ones
in the range of 0 -100
I guess you meant readExamMarks rather than readExamResults. If so, you would just need to add an if statement to check that the input value is actuall in the range [0..100]. I have also changed your loop statement for to a while because you just want to increase idx when a valid number is entered.
void readExamMarks(int examMarks[], int sizeOfArray)
{
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
int idx = 0;
while(idx < sizeOfarray)
cin >> x;
if((x >=0) && (x <= 100)){
examMarks[idx] = x;
idx++;
}
else
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
Basically you create a new array with an entry for each decade. Then iterate over the exam grades and increase the according decade in the histogram:
vector<int> calculateHistogram(vector<int> grades)
{
vector<int> histogram(10, 0);
for (int i=0; i<grades.size(); i++) {
int decade = grades[i]/10;
histogram[decade] += 1;
}
return histogram;
}