So I'm new to C++ and am writing a program to calculate the mean, median, standard deviation, min, and max of a program. The issues I'm having are that I don't know how to correctly call functions from other files in the project, and when I try to print(c out <<) my array, it returns a weird value like 0 x 0017 c 530 (disregard the spaces). If anyone could help me correctly return these functions, and print the list correctly, I would be very grateful! Here's my code (not including the .h file):
#include <iostream>
using namespace std;
#include "stats.h"
int main()
{
double nums[10000] = {};
int n;
cout << "Enter number of values: ";
cin >> n;
for (int i = 1; i <=n; i++) {
cout << "Enter number " << i << ": ";
cin >> nums[i-1];
}
// me trying to print the nu ms list
cout << nums << endl;
// me trying to call the function
double mean(double nums[], int n);
return 0;
}
stats. cpp
#include "stats.h"
double mean(double nums[], int n)
{
double sum = 0;
double average;
for (int i = 0; i > n; i++) {
sum += nums[i];
}
average = sum / n;
return average;
}
Instead of
cout << nums << endl;
Just like you have a loop to enter one value at a time in an array, you also need a similar loop to print one value at a time from the array.
To call a function from another translation unit, you would typically declare the function in a header file, your stats.h would be an excellent candidate:
double mean(double nums[], int n);
And then just invoke it from your main:
std::cout << mean(nums, n) << std::endl;
That's it.
Also:
using namespace std;
You need to have someone help you to get an amnesia, and completely forget that C++ has anything like this. This is bad programming practice.
double mean(double nums[], int n); is declaration of function, not invoking of function. You should
double mean_value = mean(nums, n);
cout << mean_value << endl;
And cout << nums << endl; won't print out the elements of the array, just the address of the array. You need to loop the array to print out all the elements.
Related
#include <iostream>
using namespace std;
// prototype functions
void DisplayResult(float MaxOrMin);
float FindMinimum(float Array[5]);
float FindMaximum(float Array[5]);
//Global Variables
float Array[5];
float MaxOrMin = 3;
float FindMin;
float FindMax;
//Main Function
int main()
{
cout << "Please enter 5 numbers: " << endl;
for (int i=0; i<5; i++)
{
cin >> Array[i]; // input for array
}
cout << "Please enter '0' for minimum or '9' for maximum:" << endl;
cin >> MaxOrMin; // input 0 or 9 for min or max
//Calling Functions
FindMinimum(Array);
FindMaximum(Array);
DisplayResult(MaxOrMin);
return 0;
}
//Function to find Minimum
float FindMinimum(float Array[5])
{
float FindMin = Array[0];
for (int y=1;y<5;y++)
{
if(Array[y] < FindMin)
FindMin = Array[y];
}
return FindMin;
}
//Function to find Maximum
float FindMaximum(float Array[5])
{
float FindMax = Array[0];
for (int x=1;x<5;x++)
{
if(Array[x] > FindMax)
FindMax = Array[x];
}
return FindMax;
}
This last part is my if, else if, else funtion:
//Function to display minimum or maximum result
void DisplayResult(float MaxOrMin)
{
if (MaxOrMin == 0)
cout << "Minimum is: " << FindMin << endl;
else if (MaxOrMin == 9)
cout << "Maximum is: " << FindMax << endl;
else
cout << "Invalid Input" << endl;
}
My project is to create a program using functions to take user input on a 5 float array. Then find the max and min and display whichever the user asks for.
Here is where my problem comes in. For both max(input 9) and min(input 0) I am getting "0". However any other input correctly returns my "Invalid Input" message.
I'm not getting any errors or warnings or errors at all on eclipse. My professor has told me that my problem was likely with my void function for displaying results. I am hoping someone could point me in the right direction here.
Apologies for my formatting and/or if this question is too basic for this site.
You misunderstand how local and global variables work. Your Find* functions shadow the globals with locals and thus they don't appear to do anything.
The problem is that your FindMinimum() (and the same with FindMaximum()) function compute the minimum (maximum) in a local variable and return it but you, in main() don't receive they in correct variables
So the computed value is lost.
I mean... instead of
FindMinimum(Array);
FindMaximum(Array);
you should write
FindMin = FindMinimum(Array);
FindMax = FindMaximum(Array);
number of grades a user inputs. I am working with dynamic array allocation. I feel confident in my code, but Xcode is giving me an error in my sort function.I thought that I was doing it right, but apparently something is wrong, and I'm not entirely sure where. I am still trying to figure out dynamic memory allocation, so I'm sure that's where my error is generating from, I just don't know where the cause is. Here is my full program:
// This program demonstrates the use of dynamic arrays
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
//Function Prototypes
void sort(float *score[], int numOfScores);
int main()
{
float *scores;
int total = 0;
float average;
float numOfScores;
int count;
cout << fixed << showpoint << setprecision(2);
cout << "Enter the number of scores to be averaged and sorted.";
cin >> numOfScores;
scores = new float(numOfScores);
for ( count = 0; count < numOfScores; count++)
{
cout << "Please enter a score:" << endl;
cin >> scores[count]; }
for (count = 0; count < numOfScores; count++)
{
total = total + scores[count];
}
average = total / numOfScores;
cout << "The average score is " << average << endl;
sort(*scores, numOfScores);
delete [] scores;
return 0;
}
//*******************************************
// Sort Function
// Bubble sort is used to sort the scores
//*******************************************
void sort(float *score[], int numOfScores)
{
do
{
bool swap = false;
for (int count = 0; count < (numOfScores -1); count++)
{
if (*score[count] > *score[count+1])
{
float *temp = score[count];
score[count] = score[count+1];
score[count+1] = temp;
swap = true;
}
}
}while(swap); //This is where I'm receiving the error.
}
Thank you!
swap is local to the do...while loop so it cannot be used in the while condition. One would expect an error related to that but since you have using namespace std; and #include <algorithm> you have now introduced the std::swap function into the scope of the program
while(swap);
Is trying to convert std::swap to a function pointer but it can't as it is overloaded and it does not know which overload to use.
For further reading on why to avoid using using namespace std; see: Why is “using namespace std” in C++ considered bad practice?
So im still pretty new to C++ and have been doing a program for a while now. I think I am slowly getting it but keep getting an error "Intellisense: operand of '*' must be a pointer." on line 36 column 10. What do I need to do to fix this error? Im going to get to the other functions as i finish each one so sorry for the extra function declaration
// This program will take input from the user and calculate the
// average, median, and mode of the number of movies students see in a month.
#include <iostream>
using namespace std;
// Function prototypes
double median(int *, int);
int mode(int *, int);
int *makeArray(int);
void getMovieData(int *, int);
void selectionSort(int[], int);
double average(int *, int);
// variables
int surveyed;
int main()
{
cout << "This program will give the average, median, and mode of the number of movies students see in a month" << endl;
cout << "How many students were surveyed?" << endl;
cin >> surveyed;
int *array = new int[surveyed];
for (int i = 0; i < surveyed; ++i)
{
cout << "How many movies did student " << i + 1 << " see?" << endl;
cin >> array[i];
}
median(*array[surveyed], surveyed);
}
double median(int *array[], int num)
{
if (num % 2 != 0)
{
int temp = ((num + 1) / 2) - 1;
cout << "The median of the number of movies seen by the students is " << array[temp] << endl;
}
else
{
cout << "The median of the number of movies seen by the students is " << array[(num / 2) - 1] << " and " << array[num / 2] << endl;
}
}
Problems:
The expression *array[surveyed] used in the following line:
median(*array[surveyed], surveyed);
is not right. array[surveyed] is the surveyed-th element of the array. It is not a pointer. It doesn't make sense to dereference it.
The type of the first argument of median used in the declaration is different than the type used in the definition. The declaration seems to be right one. Change the implementation to:
double median(int *array, int num)
Fix the way you call median. Instead of
median(*array[surveyed], surveyed);
use
median(array, surveyed);
I'm trying to break this problem into function, but my problem is that I always get different sum, positive and negative count when I print out the result.
Can someone give me a hint?
Write a program that reads ten integer numbers and outputs the sum of all the positive numbers among them. The program should ignore all numbers which are less than or equal to 0. The program should also display count of positive numbers and count of negative numbers or zero.
#include <iostream>
using namespace std;
void input(int number, int positiveCount, int negativeCount, int sum);
void output(int positiveCount, int negativeCount, int sum);
int main()
{
int number, positiveCount, negativeCount, sum;
input(number, positiveCount, negativeCount, sum);
output(positiveCount, negativeCount, sum);
return 0;
}
void input(int number, int positiveCount, int negativeCount, int sum)
{
cout << "Enter 10 integers: " << endl;
for (int i = 0; i < 10; i++)
{
cin >> number;
if (number > 0)
{
positiveCount++;
sum = sum + number;
}
else
{
negativeCount++;
}
}
}
void output(int positiveCount, int negativeCount, int sum)
{
cout << sum << endl;
cout << positiveCount << endl;
cout << negativeCount << endl;
}
Your input() function needs to take its arguments by reference so it can modify them. And you need to initialize all those ints to 0 at the start or they contain garbage.
The operations you have done inside input() function is lost because the scope of the variables are only inside the function.
You need to use either pointers or reference while passing the parameters into the input() function so as not to use a local copy.
While using pointers you need to do dereferencing also.
And initialize the variable to 0 before passing to the function.
Because there is serious mistake in your program. You define four local variables in function main() and send them by value when invoking function input(). This function DO NOT modify variables defined in the function main(). It simply modify their copies. These copies is deleted when you're out of function input().
In order to modify them you should use reference:
void input(int &number, int &positiveCount, int &negativeCount, int &sum);
But it has no meaning to create four integers in function main() and to send them in the functions input() and output(). You can create four local variables in input() and then print them in this function. Then you shouldn't define function output() and you can delete it in your code. I.e. you should modify your program.
In your assignment there is written:
Write a program that reads ten integer numbers and outputs the sum of
all the positive numbers among them
So there is no need to write separate functions for this simple program. It can look like
#include <iostream>
int main()
{
const size_t N = 10;
std::cout << "Enter " << N << " integers: ";
size_t i = 0, count = 0;
long long sum = 0;
int num;
for ( ; i < N && std::cin >> num; i++ )
{
if ( num > 0 )
{
sum += num;
++count;
}
}
std::cout << "You have entered " << count << " positive numbers\n"
<< "and " << i - count << " negative numbers or seroes\n"
<< "Sum of positive numbers is " << sum << std::endl;
return 0;
}
If you want to write separate functions then for example function input could be declared as
long long input( size_t &positive_count, size_t &negative_count );
or
long long input( size_t &total_count, size_t &positive_count );
or
long long input( size_t *positive_count, size_t *negative_count );
or
long long input( size_t *total_count, size_t *positive_count );
Obviously I need a sum function for this and accumulate will not cut it
I need to create program - a vector - with n number of elements the user can prescribe - and the sum function can only sum POSITIVE elements even though the user can enter negative elements as well...
In the computeSum function I also need to add a "success" to the whole group
computeSum (dataVec, howMany, total, sucess);
and create a parameter for people who enter - all negative numbers but want to sum them but are unable to because there are no positive numbers
if (success) {
cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}
So here is what I got
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
int main()
{
vector<double> dataVec;
double i, n, howMany, total;
cout << "How many numbers would you like to put into the vector?";
cin >> n;
dataVec.resize(n);
for(vector<double>::size_type i=0;i < n;i++)
{
cout << "Enter the numbers: \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum?";
cin >> howMany;
cout << computeSum (dataVec, howMany, total);
}
double computeSum (vector<double> &Vec, howMany, total)
{
double total =0;
for(int i=0;i < howMany;i++)
total+=Vec[i];
return total;
}
I also seem to having trouble compiling just this - computeSum() is not being understood in int main(); howMany is not being understood in computerSum(); and on a gloabl scope total() and howMany() are undeclared (I guess that would mean i would need to decalre globally???)
In fact, accumulate will “cut it”, with an appropriate functor that only regards positive values:
int sum_positive(int first, int second) {
return first + (second > 0 ? second : 0);
}
…
std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);
Getting on my hobby horse: Boost Range Adaptors. Hits the sweet point with me
#include <boost/range/adaptors.hpp>
#include <boost/range/numeric.hpp>
bool isnatural(int i) { return i>=0; }
using namespace boost::adaptors;
int main(int argc, char** args)
{
static const int data[] = { -130, -1543, 4018, 5542, -4389, 15266, };
std::cout << "sum: " << boost::accumulate(data | filtered(isnatural), 0) << std::endl;
return 0;
}
Output:
sum: 24826
With C++11 awesomeness1 spice:
std::cout << "sum: " << boost::accumulate(data
| filtered([] (int i) { return i>=0; }), 0) << std::endl;
1: to be honest, I really hate the clumsyness of lambda syntax:
having to specify the parameter type always
having to spell out the return statement to
For this scenario, it seems to that filtered([] (i) { i>=0 })
could be figured out by the compiler. Well, perhaps in c++22 :)
Your computeSum() function must appear above your main() function in the source file for it to be in scope. Also in your computeSum() function signature you haven't given types to the howMany and total variables. I'm guessing they should be double howMany and double total?