Ok so everything is working except that the sorted data is sometimes outputting whole numbers rather than a decimal number. This seems like an easy mistake to fix, but I can't find it!
#include <iostream>
using namespace std;
void input (double x[], int length);
void copy (double source[], double dest[], int length);
void sort (double x[], int length);
void display (double x[], int length);
int main()
{
double data[20];
double sdata[20];
int itemcount;
cout << "Enter data item count <1-20>" << endl;
cin >> itemcount;
if ((itemcount < 1) || (itemcount > 20))
{
cout << "Class size is NOT within required range. The required range is 1 to 20." << endl;
cout << "Bye." << endl;
return (0);
}
input (data, itemcount);
cout << "Original Data:" << endl;
copy (data, sdata, itemcount);
display (sdata, itemcount);
sort (sdata, itemcount);
cout << "Sorted Data" << endl;
display (sdata, itemcount);
}
void input (double x[], int length)
{
int i;
for (i=0; i < length; i++)
{
cout << "Enter score" << endl;
cin >> x[i];
}
}
void copy (double source[], double dest[], int length)
{
int i;
for (i=0; i < length; i++)
{
dest[i] = source[i];
}
}
void sort (double x[], int length)
{
int i, temp;
bool swapdone = true;
while (swapdone)
{
swapdone = false;
for (i=0; i < length-1; i++)
{
if (x[i] > x[i+1])
{
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
swapdone = true;
}
}
}
}
void display (double x[], int length)
{
int i;
for (i=0; i < length; i++)
{
cout << x[i] << " ";
}
cout << endl;
}
In an example run, the result is:
Enter data item count <1-20>
5
Enter score
30.41
Enter score
63.25
Enter score
62.47
Enter score
40.25
Enter score
310.41
Original Data:
30.41 63.25 62.47 40.25 310.41
Sorted Data
30.41 40.25 62 63 310.41
temp should be a double, not an int, if you don't want things you assign to it to become integers.
If you use "i" only as counter then you can declare it inside the for loop such as
for (int i=0;i<length;i++)
This will save some trouble. Anyway,
Change
int i, temp;
to
int i;
double temp;
Double means it can hold decimal numbers, integer means whole numbers. When you are swapping around to do the bubble sort, it is converting your double to integer type. Your compiler should given a type conversion error, but should compile.
Check
int i, temp;
temp must be double!
Try this:
double tmp;
std::cout << ios_base::setpercision(3) << tmp;
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 :|
"Write a function, named sums(), that has two input parameters; an array of floats; and an integer,
n, which is the number of values stored in the array. Compute the sum of the positive values in the array
and the sum of the negative values. Also count the number of values in each category. Return these four
answers through output reference parameters.
Write a main program that reads no more than 10 real numbers and stores them in an array. Stop reading numbers when a 0 is entered. Call the sums() function and print the answers it returns. Also compute and print the average values of the positive and negative sets."
#include <iostream>
using namespace std;
void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt);
double input(double UserInput);
int main()
{
float data[10];
int count = 10 ;
double UserInput = 0;
float posSum=0.0, negSum=0.0; //sum of positives and negatives
int posCnt =0, negCnt=0; // count of postive and negatives
input(UserInput);
sums(data, count, posSum,posCnt, negSum, negCnt);
cout << "Positive sum: " << posSum << endl;
cout << "Positive count:" << posCnt << endl;
cout << "Negative sum: " << negSum << endl;
cout << "Negative count:" << negCnt << endl;
return 0;
}
double input(double UserInput) {
for(int i = 0; i < 10; i++){
cout << "Enter a real number or '0' to stop: " ;
cin >> UserInput;
if(UserInput == 0)break;
data[i] = UserInput;
}
return UserInput;
}
void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt){
int i;
for(i = 0; i < count; i++){
if(data[i] > 0){
posCnt += 1;
posSum += data[i];
}
else{
negCnt += 1;
negSum += data[i];
}
}
}
It gives me an error when trying to compile it saying "use of undeclared identifier 'data'" on line 32 in the input function.
It is because the data is not declared in the function input, you should use a float pointer.
void input(float *data)
{
float UserInput;
for (int i = 0; i < 10; i++)
{
cout << "Enter a real number or '0' to stop: ";
cin >> UserInput;
if (UserInput == 0)break;
data[i] = UserInput;
}
return;
}
int main()
{
float *data;
data = (float*)malloc(10 * sizeof(float));
input(data);
cout << data[0];
free(data);
system("pause");
return 0;
}
This should be an accurate example. Good Luck with your following homework.
So this is a program I wrote for a CS lab in my class. It was modified so that it would take in input from a text file and output to another text file. After it does the calculations, it asks the user if they want to rerun the program, which is just a while loop in main. Why do I get this error when I the program reruns?
Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffeb1d82bc8)
it occurs at this line in the getPints function:
bloodInFile >> a[i];
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
#include <fstream>
using namespace std;
const int MAX_HOURS = 7;
void getPints(double a[], int h);
double getAverage(double a[], int h);
double getHigh(double a[], int h);
double getLow(double a[], int h);
void displayInfo(double a, double b, double c);
int main()
{
string again = "yes";
double pints[MAX_HOURS];
double getHigh(double pints[], int MAX_HOURS);
while (again == "yes")
{
getPints(pints, MAX_HOURS);
getHigh(pints, MAX_HOURS);
displayInfo(getAverage(pints, MAX_HOURS), getHigh(pints, MAX_HOURS), getLow(pints, MAX_HOURS));
cout << "Do you want to run again (yes or no)? ";
cin >> again;
}
return 0;
}
void getPints(double a[], int h)
{
int i;
ifstream bloodInFile;
bloodInFile.open("bloodDrive.txt");
if (!bloodInFile)
cout << "Cannot open file." << endl;
while (!bloodInFile.eof())
{
bloodInFile >> a[i];
i++;
}
bloodInFile.close();
}
double getAverage(double a[], int h)
{
int i;
double totalPints = 0;
double averagePints;
for (i = 0; i <= h - 1; i++)
totalPints = totalPints + a[i];
averagePints = totalPints / i;
return averagePints;
}
double getHigh(double a[], int h)
{
int i;
double highest = a[0];
for (i = 1; i < h; i++)
{
if (a[i] > highest)
highest = a[i];
}
return highest;
}
double getLow(double a[], int h)
{
int i;
double lowest = a[0];
for (i = 1; i < h; i++)
{
if (a[i] < lowest)
lowest = a[i];
}
return lowest;
}
void displayInfo(double a, double b, double c)
{
ofstream bloodOutFile;
bloodOutFile.open("bloodResults.txt");
bloodOutFile << "Average pints: " << setprecision(1) << showpoint<< fixed << a << endl;
bloodOutFile << "Highest pints: " << setprecision(1) << showpoint<< fixed << b << endl;
bloodOutFile << "Lowest pints: " << setprecision(1) << showpoint<< fixed << c << endl;
}
Check that you are not out of bound of array a in function getPints add check here
while (!bloodInFile.eof())
{
if(i >= h)
break;
bloodInFile >> a[i];
i++;
}
Because if you can have more lines that MAX_HOURS in bloodDrive.txt file. Also I don't see that you initialize i somewhere i suppose it should be equal to 0 (i=0), so you're function should looks like that
void getPints(double a[], int h)
{
int i = 0;
ifstream bloodInFile;
bloodInFile.open("bloodDrive.txt");
if (!bloodInFile)
cout << "Cannot open file." << endl;
while (!bloodInFile.eof())
{
if(i > h)
break;
bloodInFile >> a[i];
i++;
}
bloodInFile.close();
}
P.S. as #JonathanLeffler said (and I agree with him 100%) it's better to use dynamic array (vector e.g.) for such problem when you don't know how much input could be.
The problem I am having with my program is, first, when I calculate percent, it's not adding all the elements in the array to a total and diving them from. I tried putting the total += percents[i]; in a nested for-loop, but it just gave me negative %.
Also, my total at the end won't display anything. At first, I had it and all the function defined in the main(), but it didn't do anything. Even after the change, it doesn't work. Also, last thing, my file has 20 items, yet the loops only read in 19 items. If I change to 20, it crashes.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void inputValues(string names[], int votes[])
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < 19; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
double *calcPercents( double percents[], int votes[], double total)
{
for(int i = 0; i < 19; i++)
{
percents[i] = votes[i];
total += percents[i];
percents[i] = (percents[i]/total)*100;
}
return percents;
}
string determineWinner(string names[], double percents[])
{
double temp = 0;
string winner;
for(int i = 0; i < 19; i++)
{
if(percents[i] > temp)
{
temp = percents[i];
winner = names[i];
}
}
return winner;
}
void displayResults(string names[], int votes[], double percents[])
{
int total = 0;
calcPercents(percents, votes, total);
cout << "Candidate Votes Received % of Total Votes " << endl;
for(int i = 0; i < 19; i++)
{
cout << names[i] << " " << votes[i] << " " << percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is " << determineWinner(names, percents) << endl;
}
int main()
{
string names[19], winner;
int votes[19];
double percents[19];
inputValues(names, votes);
displayResults(names, votes, percents);
}
My file is in the style:
bob (tab) 1254
joe (tab) 768
etc.
If you have to use arrays instead of std::vectors you should pass their size to the functions using them. One way is to set the size using a constant, like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // bad practice
const int size = 20;
void inputValues(string names[], int votes[], int n);
// add the size as a parameter of the function ^^^^
int calcPercents( double percents[], int votes[], int n );
//^^ I'll explain later why I changed your signature ^^^
string determineWinner(string names[], double percents[], int n );
void displayResults(string names[], int votes[], double percents[], int n);
int main()
{
// It's always better to initialize the variables to avoid undefined behavior
// like the negative percentages you have noticed
string names[size] ="";
int votes[size] = {0};
double percents[size] = {0.0};
inputValues(names, votes, size);
displayResults(names, votes, percents, size);
}
To calculate the percentages you can use two loops, one for the sum and the other to get the percentage. In your function you pass total as a parameter by value, so it will be copied and the changes will never be visible outside the function. I choose to return that vaule, even if doing so the name of function becomes a litle misleading:
int calcPercents( double percents[], int votes[], int n )
{
int total = 0;
for(int i = 0; i < n; i++)
// note the bound ^^^
{
total += votes[i];
}
double factor = 100.0 / total;
for(int i = 0; i < n; i++)
{
percents[i] = factor * votes[i];
}
return total;
}
You should also add some checks to the input function, I only add the size parameter. Note that having initialized the arrays, even if it fails reading the file the arrays doesn't contain random values:
void inputValues(string names[], int votes[], int n)
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < n; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
I'd change the function which determine the winner too:
string determineWinner(string names[], double percents[], int n )
{
if ( !n )
{
return "";
}
double max = percents[0];
// update an index instead of a string
int winner = 0;
for( int i = 1; i < n; i++ )
{
if( percents[i] > max )
{
max = percents[i];
winner = i;
}
}
return names[winner];
}
For the last function, only remember to add the size:
void displayResults(string names[], int votes[], double percents[], int n)
{
int total = calcPercents(percents, votes, n);
cout << "Candidate Votes Received % of Total Votes " << endl;
for( int i = 0; i < n; i++ )
{
cout << names[i] << " " << votes[i] << " "
<< percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is "
<< determineWinner(names, percents,n) << endl;
}
So for my problem I need to have a dynamically allocated array that is to be created in the main function and populated in another function. The issue I'm having is that I then need to use that array in other functions and my array has no value after I populate it in my function (or at least this seems to be the case) Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
//prototypes
int getNumber();
void getMovieData(int *ptrToArray, int arraySize);
void sort(int *ptrToArray, int arraySize);
double getAverage(int *ptrToArray, int arraySize);
void print(int *ptrToArray, int arraySize);
int main()
{
int stuNum = 0;
int* stuArray;
stuArray = new int[stuNum];
getMovieData(stuArray, stuNum);
cout << "--- Here is the data you entered ---" << endl;
print(stuArray, stuNum);
sort(stuArray, stuNum);
cout << "--- Here is the data you entered sorted ---" << endl;
print(stuArray, stuNum);
cout << fixed << setprecision(2);
cout << "Here is the average of your survey" << getAverage(stuArray, stuNum) << endl;
system("pause");
return 0;
}
int getNumber()
{
int userNum;
cin >> userNum;
while (userNum <= 0)
{
cout << "Error number must be greater than zero." << endl;
cin >> userNum;
}
return userNum;
}
void getMovieData(int *ptrToArray, int arraySize)
{
cout << "Enter the number of students being surveyed: ";
arraySize = getNumber();
for (int i = 0; i < arraySize; i++)
{
cout << "Enter the movies seen by Student " << i + 1 << ": ";
ptrToArray[i] = getNumber();
}
return;
}
void sort(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
for (int j = 0; j < arraySize - 1; j++)
{
if (ptrToArray[j] > ptrToArray[j + 1])
{
int temp = ptrToArray[j];
ptrToArray[j] = ptrToArray[j + 1];
ptrToArray[j + 1] = temp;
}
}
}
}
double getAverage(int *ptrToArray, int arraySize)
{
int total = 0;
for (int i = 0; i < arraySize; i++) { total = total + ptrToArray[i]; }
return total;
}
void print(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++) { cout << ptrToArray[i] << "\t"; }
cout << endl;
}
You are allocating an array with zero elements. Change the value of stuNum to a positive number representing the number ints you need.