How to calculate mean using calling function in C++? - c++

The functions are getInputN(), calculateMean() & displayData().
So to be really clear, these are the requirements.
getInputN function: Should accept the number of the value, N as an integer as argument and ask the user to enter the value of N number. Then, return the sum of the value as a double.
calculateMean function: Should accept the number of the value, N and sum of the value as arguments. Then return the mean as a double.
displayData function: Should accept the mean as argument. Then, display them in the appropriate message on screen. No return value required for this function.
If I run the code, it will display Average = inf
p/s: I'm really sorry for the confusing question at first. I'm really new to this website and this is my very first question. It took me some times to figure out things to ask properly in this platform. I hope you guys understand and once again, sorry for the inconvenience. Thank you for the helps too :)
Here is my code:
#include <iostream>
using namespace std;
int getInputN(int n);
float calculateMean (int n, float sum);
float displayData(double mean);
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN(n);
calculateMean (n, sum);
displayData(mean);
return 0;
}
int getInputN(int n)
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean (int n, float sum)
{
mean = sum/n;
return mean;
}
//function to display the mean
float displayData (double mean)
{
cout << "Average = " << mean;
}

The argument int n in the function getInputN is shadowing (hiding) the global variable n. This prevents the global variable from being updated and sum is divided by zero (the default value of gloval variable without explicit initialization).
If you want to pass data using gloval variables, the arguments should be removed because one of that (n as descrived above) is harmful and other are redundant.
Also the function displayData is declared to return float but didn't execute any return statement. This invokes undefined behavior. I fixed this by changing its return type to void.
#include <iostream>
using namespace std;
int getInputN();
float calculateMean ();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean ();
displayData();
return 0;
}
int getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean ()
{
mean = sum/n;
return mean;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
This fix will make the code work, but there should be better design without usage of global variables. References is useful to have functions modify things given as arguments and std::vector is useful to return "arrays".

The variable n in int getInputN(int n) is used in the function instead of the global n declared. As such, using global n (which is uninitialized till that point initialized to 0) to calculate mean = sum/n will lead to a undefined behavior divide by 0 error, resulting in inf.
More info :
Uninitialized variable behaviour in C++
C++ global and local variables
Also, the function float displayData (double mean) doesn't return any value, causing another undefined behavior.
More info :
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
Modified code :
#include <iostream>
using namespace std;
void getInputN();
void calculateMean();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean();
displayData();
return 0;
}
void getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
}
//function to calculate the mean
void calculateMean ()
{
mean = sum/n;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
Result :
Enter the numbers of data: 3
1. Enter number: 1
2. Enter number: 3
3. Enter number: 6
Average = 3.33333
Furthermore, if you don't use the numbers for anything else, declaring a float num[50]; is quite pointless. Also, noted that using global variable and using namespace std; is not recommended.
#include <iostream>
const int maxn = 50;
const int minn = 1;
int main()
{
int n; std::cout << "Enter N : "; std::cin >> n;
while (n < minn || n > maxn) {std::cout << "Invalid. Re-enter N : "; std::cin >> n;}
double sum = 0; int tmp;
for (int i = 0; i < n; i++) { std::cout << "Enter number " << i+1 << " : "; std::cin >> tmp; sum += tmp;}
std::cout << "Average : " << sum/n;
}
Result :
Enter N : 3
Enter number 1 : 25
Enter number 2 : 97
Enter number 3 : 111
Average : 77.6667

Knowing how the functions are behaved, we can write implementations that work nicely and don't use any global variables at all.
#include <iostream>
double getInputN(int n);
double calculateMean(int n, double sum);
void displayData(double mean);
int main()
{
//User enter the number of value
int numEntries;
std::cout << "Enter the numbers of data: ";
std::cin >> numEntries;
//if user input more than 50 numbers
while (numEntries > 50 || numEntries <= 0)
{
std::cout << "Invalid! Enter the number in range of (1 to 50)." << std::endl;
std::cout << "Enter the number of data: ";
std::cin >> numEntries;
}
// Get user input
double sum = getInputN(numEntries);
double mean = calculateMean(numEntries, sum);
displayData(mean);
return 0;
}
double getInputN(int n)
{
double sum = 0.;
for (int i = 0; i < n; ++i)
{
double userInput;
std::cout << i + 1 << ". Enter number: ";
std::cin >> userInput;
sum += userInput;
}
return sum;
}
//function to calculate the mean
double calculateMean(int n, double sum)
{
double mean = sum / n;
return mean;
}
//function to display the mean
void displayData(double mean)
{
std::cout << "Average = " << mean;
}
Let's go into some more detail on each of the changes.
First, I've changed the signatures of all of your functions. getInputN is supposed to return a double, not an int. calculateMean is supposed to accept and return a double, not a float. And displayData isn't required to return anything, it doesn't make sense for it to return anything, and therefore I've made its return type void.
Second, note that I've moved the code for figuring out how many entries to enter from getInputN into main. The reason for this is that the sole argument to getInputN is "how many inputs should we get?", so we need to know its value before we call getInputN.
Third, note how I've used the return values from each function in the calling code. In main, when I write double sum = getInputN(numEntries);, that declares a variable sum and stores the return value of getInputN(numEntries) to sum. When you just write getInputN(n);, the return value from getInputN is discarded. By storing it in a variable in main, I can then pass its value to another function, like in the next line where I've written double mean = calculateMean(numEntries, sum);.
Fourth, note how the requirements of the question are such that I no longer use any kind of array whatsoever. getInputN doesn't bother tracking each individual entry, because all we care about is the final sum at the end.

Related

use of undeclared identifier 'data' C++

"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.

SUM function within for loop, C++

Looking for some insight on how to calculate a sum of user inputted numbers within a for statement and print it after the for loop has been completed.
So far I have this code:
//this code will sort 2 numbers then print them in ascending order and
before exiting, add them all together
// then average them
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z, sort1, sort2;
for (n=0;n<3;n++){
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
if (m>z){
sort1 = z;
sort2 = m;
}
else{
sort1 = m;
sort2 = z;
}
cout << sort1 << sort2 << endl;
}
int sum = m+z;
int sum2 = m+z+sum;
float sum3= m+z+sum2;
cout << " sum of all numbers entered: " << sum << endl;
cout << " average of the numberes entered: " << sum3 /6 << endl;
}
So I know that the sum function i have is incorrect, it only evaluates the last m+z entered by the user and not the others. If i put the sum function in the loop, once it breaks, it dumps all information within the loop rendering the sum value obsolete. Wondering if there's another way to achieve the sum function within the loop but only print once outside the loop.
Are there any other loops that don't delete information within the loop that you can extract outside?
All loops in C++ are scoped, that means that any variables declared within a scope are not accessible outside (of the scope) nor will they persist to the next iteration.
int sum = 0; // declare sum outside of loop
for(int n = 0; 0 < 3; n++)
{
int m, z; // These will be reset every iteration of the for loop
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
/*
Sort and print goes here...
*/
sum += m + z;
}
std::cout << "The sum: " << sum <<std::endl;
#include<iostream>
using namespace std;
int main()
{
int total = 0, i, j, sort1, sort2;
//this For-Loop will loop three times, every time getting two new
//integer from the user
for (int c = 0; c < 3; c++) {
cout << "Enter two integers ( n n ): ";
cin >> i;
cin >> j;
//This will compare if first number is bigger than the second one. If it
//is, then second number is the smallest
if (i > j) {
sort1 = j;
sort2 = i;
}
else {
sort1 = i;
sort2 = j;
}
cout << "The numbers are: " << sort1 << " and " << sort2 << endl;
//This statement will add into the variable total, the sum of both numbers entered before doing another loop around
total += i + j;
}
cout << "The sum of all integers entered is: " << total << endl;
system("pause");
return 0;
}

How do I pass a user input as an argument into a function prototype?

#include <iostream>
#include <cmath>
using namespace std;
int nCount = 0, nX = 0;
double sum_total, nAverage;
// Function Prototypes
int Sum(int number); // Returns the sum of two ints
int Max(int i, int j); // Returns max of two ints
int Min(int i, int j); // Returns min of two ints
double Average(int nCount, int sum_total); // Returns the avg - (sum_total/count)
int main(){
cout << "How many numbers would you like to enter?" << endl;
cin >> nCount;
cout << "You would like to enter " << nCount << " numbers\n";
while (nX < nCount)
{
int a;
cout << "Please enter you numbers: "; // Pass this value into functions
cin >> a;
// Call Sum, Max, Min, and Average passing these two arguments
int Sum(a);
nX++;
}
cout << "The total is: " << sum_total << endl;
system("PAUSE");
return 0;
}
int Sum(int number)
{
sum_total = number + number;
return sum_total;
}
This is the program I am working on. What I would like to do is have the user enter any number of integers using cin and then pass that value into the function int Sum to add all the numbers together and then display the sum of them. The while loop allows the user to enter how ever many numbers they would like, and then that argument is passed into the next function. This program however will return 0 as the sum. What is the reason for 0 being displayed? And what do I need to do in order to make this program work?
EDIT
int Max(int number)
{
if (number > currentMax)
currentMax = number;
return currentMax;
}
//
int Min(int number)
{
if (currentMin < number)
currentMin = number;
return currentMin;
}
Your function call is invalid. You should call it like so:
Sum(a);
Also, because sum_total is a global variable, you don't need to return a value from Sum.
EDIT
Here is the appropriate Sum() definition as well:
void Sum(int number)
{
sum_total += number;
}
Note: don't forget to initialize sum_total to 0.

Using fractional base when summing taylor series causes infinite loop?

I am trying to write a program that will approximate e^x using taylor series as follows:
I created a function that will do the summation, taking in n (number of times to sum) and x (the exponent) and another function that takes in a number and returns its factorial. Pretty simple stuff I think. The problem I'm having is when I input a fractional x first (for instance, .5, 6) the program just hangs. If I first input something like (3, 6) and then after that calculation, I input (.5, 6)I will get an infinite loop. If the x I input is not a fraction, I can do the calculation as many times as I like.
I feel that it must have something to do with my call to the pow() function. I think I'm using it correctly (pow(double, int)) but does it not take fractions or something? I don't understand.
Here's my code:
double taylorSeries (double x, int n, double &error)
{
double sum = 0;
for (int i=0; i <= n; i++)
sum += (pow (x, i))/(factorial (i));
error = (fabs(exp(x) - sum));
return sum;
}
long factorial(int n)
{
long factorial=0;
for (int i = 0; i <= n; i++){
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
return factorial;
}
And then the call to the taylorSeries function in main looks like this:
cout << "please enter x and n: ";
cin >> x >> n;
cout << "taylor series sum = " ;
cout << taylorSeries (x, n, error) << endl;
//cout << "error = " << error;
Can someone help me figure out why this isn't working?
Never mind some of the inefficiencies of your algorithm, the most likely cause for your function seemingly fail to return is a bad parsing of x and thus n not getting set at all, which means it could hold any random value.
Your line:
cin >> x >> n;
If it fails to parse into x properly then it will not attempt to parse the next number because the input stream will be in an error state.
If n has not been initialised it could hold any value which might in reality be an extremely big integer. Thus your algorithm appears not to ever return.
int main()
{
double x = 0.0;
int n = 0;
double error = 0;
cout << "please enter x and n: ";
cin >> x >> n;
if( cin )
{
cout << "taylor series sum, x=" << x << " n=" << n << " : ";
cout << taylorSeries (x, n, error) << endl;
cout << "error = " << error;
}
else
{
cerr << "invalid input" << endl;
}
}
For a more efficient algorithm:
double taylorSeries (double x, int n, double &error)
{
double sum = 1;
double xpow = x; // would start at 1 but we have implemented exponent of 0
double fact = 1;
for (int i=1; i <= n; i++)
{
fact *= i;
sum += xpow / fact;
xpow *= x;
}
error = fabs(exp(x) - sum);
return sum;
}
Your factorial function is technically correct until the point where it will overflow.

Storing individual numbers of an int in an array

I was trying to write a program in which I take an input number,
example 891 and input each of these number in an array for example
x[0] = 8, x[1] = 9 and x[2] = 1
I was trying to use recursion to implement my method:
void calc(int val, int k)
{
static int number = val;
if((val/10))
{
calc(val/10, k--);
}
int x = number - val*pow(10, k);
cout << x << ", k = " << k << " and number = " << number << endl;
}
int main()
{
//write a program that converts a number to string
int number;
cout << "Enter a number: ";
cin >> number;
number = 891;
int k = 0;
//while(number/10 != 0)
k = 2;
calc(number, k);
}
Basically I'm trying to use my recursive function to try to break the
number down in its finer parts, however I get an output of (in val):
91, 1, -8019. Is there a way I can improve on this, but maintaining
the structure?
Both putting your data into an array and solving this problem recursively requires a bit of pointer arithmetic.
You'll need to allocate your array ahead of time, which means you need to know the number of digits. You'll also need to pass around the pointer to the array so that recursive calls can assign to it.
Below is a shortish solution that fits both of these requirements.
#import <math.h>
#import <iostream>
using namespace std;
void calc(int num, int* digs) {
if (num > 0) {
calc(num/10, digs-1); //recursive call, doing head recursion
*digs = num %10; //assigning this digit
}
}
int main() {
//Get number from user
int inputNumber;
cout << "Input a number: ";
cin >> inputNumber;
int numDigits = log10(inputNumber) + 1;
int outputArray[numDigits];
//I give a pointer to the end of the array
//This is because we are receiving digits from the end
//So we traverse backwards from the end of the array
calc(inputNumber, outputArray+numDigits-1);
//Following is not logic, just printing
for (int i=0; i < numDigits; i++) {
cout << outputArray[i] << " ";
}
cout << endl;
}
void calc(int val)
{
cout << "digit:"<<val % 10<< " and number = " << val << endl;
if((val/10))
{
calc(val/10);
}
}
This will print out each digit (which looks like what you are trying to do in the function).