I need help finding the error in this code. It's supposed to find the average of the input numbers that are not divisible by 2 or 3.
#include <iostream>
using namespace std;
void enterarray(int a[], int &n) {
cout << "please enter n: ";
cin >> n;
for(int i = 0; i < n; i )
cin >> a[i];
}
double average(int a[100], int n)
{
int t = 0, count;
for(int i = 0; i < n; i )
if( a[i] % 2 == 0 && a[i] % 3 == 0) {
t = t a[i];
count ;
}
return t * 1.0 / count;
}
int main()
{
int a[100];
int n;
enterarray(a, n);
cout << average(a, n);
return 0;
}
CodePudding user response:
count needs to be initialized.
int t=0, count=0;
n needs to be initialized in main.
int n = 0;
enterarray(int a[], int &n)
could do with bounds checking n is less-equal to 100.
CodePudding user response:
The problem is that your count
variable is uninitialized and
any uninitialized local/block scope built in type variable has a garbage value.
using(accessing) which can lead to undefined behavior.
The solution would be to initialize count
like:
int t = 0, count = 0;
Problem 2: Note also that before dividing t
by count
you should check that count!=0
. That is, if count
is zero you could simply return 0
instead of dividing by 0
as i have done in the below shown program.
The below shown program uses std::vector
instead of array.
#include <iostream>
#include <vector>
using namespace std;
//the first argument is a vector of int passed by reference
void enterarray(std::vector<int> &a, int &n) {
cout<<"please enter n: ";
cin >> n;
int elem;
for(int i=0; i<n; i )
{
cin >> elem;
a.emplace_back(elem);
}
}
//no need to pass n because we can find the size of the vector using size() member function
double average(const std::vector<int> &a) {
int t=0, count = 0;//initialize count and t to 0
for(const int &element: a){
std::cout<<element<<std::endl;
if( element % 2 == 0 && (element % 3 == 0)) {
t = t element;
count ;
}
}
//make sure you don't divide by zero
return (count > 0 ?(t * 1.0) / count: 0);
}
int main() {
//create a vector instead of an array
std::vector<int> a;
int n = 0;
enterarray(a, n);
cout<<average(a);//no need to pass n
return 0;
}