Question: debug the following code. the program should return 1.5. the program will have an object 'i' that contains a counter and an array of numbers.
debug the following code. the program should return 1.5. the program will have an object 'i' that contains a counter and an array of numbers. in the end, it will call avg() to sum the numbers in the array and divide by counter and return the result. please use c++.
#include
using std::cout, std::endl;
struct Number {
int x;
Number () : x() {}
Number (int _x) : x(_x) {}
};
class res {
private:
int counter; //use to count the number of nums
Number** nums; //stores an array of nums
double *avg; //stores average
public:
res (int _counter) { //declare the amount of number we'll use
counter = _counter;
nums = new Number*[counter];
}
~res () {
for (int i=0; i<=counter;i++) {
delete[] nums[i];
}
}
void add_all_nums (Number *pt /*unsized array */) {
for (int i = 0; i <= counter; i++) {
nums[i]=new Number();
memcpy(nums[i], &pt[i%counter], sizeof(Number));
}
}
double* avg () {
int sum;
for (int i = 0; i <= counter; i++) {
sum+=nums[i]->x;
}
avg = new double(sum/counter);
return avg;
}
};
int main () {
Number i1;
i1.x = 0;
Number i2;
i2.x=1;
Number i3;
i3.x = 2;
//fix this code
Number pts[3] = {i1, i2, i3};
res i = res(3); //declare res i with a counter of 3
i.add_all_nums(pts); // add numbers to the i object's array
cout<<"average = "< }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
