"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.
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 :|
I want the program to ask the user to enter a number and then that function in the array will display on the screen
e.g
case 0 = displayNums (displays numbers entered by the user)
case 2 = getAverage (gets average of numbers entered)
I tried to code the menu to do that, but it only shows up. Nothing happens when the number for the specific function is entered.
#include <iostream>
#define integer 12
int ShowMenu(void);
double displayNums(double[], int);
double GetTotal(double[], int);
double getAverage(double[], int);
double getLargest(double[], int, int*);
double getSmallest(double[], int, int*);
int getNumOccurence(double[], int, int n);
double scaleUp(double[], int);
using namespace std;
int main() {
cout << "enter 12 integers 1 by 1:\n";
int data;
int n = 1;
// array to hold the integers
double arr[integer];
// get the integers
for (int i = 0; i < 12; i++) {
cin >> arr[i];
}
int option;
do {
option = ShowMenu();
switch (option) {
case 0:
double displayNums();
break;
case 1:
double GetTotal();
break;
case 2:
double getAverage();
break;
case 3:
double getLargest();
break;
case 4:
double getSmallest();
break;
case 5:
int getNumOccurence();
break;
case 6:
double scaleUp();
break;
case 7:
break;
default:
cout << "invalid option\n";
}
} while (option != 7);
// displays numbers entered by user
cout << displayNums(arr, integer) << endl;
// displays sum of numbers entered
cout << GetTotal(arr, integer) << endl;
// displays the average
cout << "Average integer is:" << getAverage(arr, integer) << endl;
// displays the largest
cout << "Largest integer is: " << getLargest(arr, integer, &data) << endl;
// display the smallest integer
cout << "Smallest integer is:" << getSmallest(arr, integer, &data) << endl;
// display the occurence of the num
cout << "Occurence integer is:" << getNumOccurence(arr, integer, n) << endl;
// display the scale up integers
cout << "Scaled up integers are:" << scaleUp(arr, integer) << endl;
return 0;
}
int ShowMenu(void) {
int option;
cout << "\t0. Display Numbers\n";
cout << "\t1. Get Total of numbers\n";
cout << "\t2. Get Average\n";
cout << "\t3. Get Largest\n";
cout << "\t4. Get Smallest\n";
cout << "\t5. Get Number Occurences\n";
cout << "\t6. Scale Up\n";
cout << "\t7. Quit\n";
cout << "\t\t\tOption ? ";
cin >> option;
return option;
}
double displayNums(double arr[], int size) {
double display = 0;
for (int i = 0; i < size; i++) { // for loop
}
cout << "the numbers that you have entered into the array are:" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << endl; // displays numbers entered
}
return display;
}
double GetTotal(double arr[], int size) {
double sum = 0;
for (int i = 0; i < size; i++) {
}
cout << "" << endl;
for (int i = 0; i < 12; i++) {
sum += arr[i];
}
cout << "The sum of all numbers entered is:" << sum << endl;
return sum;
}
double getAverage(double arr[], int size) {
double sum = 0.0, avg;
for (int i = 0; i < size; i++) {
sum = sum + arr[i];
}
avg = sum / size;
return avg;
}
double getLargest(double arr[], int size, int* data) {
double large = 0;
for (int i = 0; i < size; i++) {
if (arr[i] > large) {
large = arr[i];
*data = i + 1;
}
}
return large;
}
double getSmallest(double arr[], int size, int* data) {
double small = 10000;
for (int i = 0; i < size; i++) {
if (arr[i] < small) {
small = arr[i];
*data = i + 1;
}
}
return small;
}
int getNumOccurence(double arr[], int size, int n) {
// only works when you insert repetable number 1
int count = 0;
for (int i = 0; i < size; i++) {
if (n == arr[i]) {
count++;
}
}
return count;
}
double scaleUp(double arr[], int size) {
int factor = 0;
cout << "enter the scale up factor";
cin >> factor;
for (int i = 0; i < size; i++) {
arr[i] *= factor;
cout << arr[i] << endl;
}
return factor;
}
You could use a std::map instead of all those cases.
// Declare a synonym for a function pointer
typedef double (*Function_Pointer)();
// Declare an abbreviation for the map:
typedef std::map<int, Function_Pointer> Function_Display_Table;
// Initialize the function table:
Function_Display_Table display_table;
display_table[0] = display_nums;
display_table[1] = GetTotal;
display_table[2] = getAverage();
//...
// To process your selection:
Function_Pointer fp = display_table.at(selection);
double return_value = fp();
To expand your menu selection, you only have to add rows to the display_table.
(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}
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;
}
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;