Chris Ashkar Chris Ashkar - 1 month ago 6
C++ Question

Pointer variable using float inside an array to calculate the average C++

I am trying to calculate the float using pointer variable, but I am getting an error that I cannot convert 'float*' to 'int*' in initialization. Any ideas how I would go on converting a float to an integer? Thanks a lot.

int main()
{
float arr[SIZE]={1.1,2.2,3.3,4.4,5.5};
int sum, average, avg=0;
int* end=arr+SIZE;
for(int* ptr=arr; ptr<end; ptr++)
{
sum+= *ptr;
avg = average/sum;

}
cout << "The sum is " << sum;
cout << "The average is " << avg;

}

Answer

you can solve it by: append 'f' to each value in the array also only calculate the average outside the loop no inside so in your program you are calculating avg after each sum!!

const int SIZE = 5; // or #define SIZE 5 // I recommend using const
float arr[SIZE] = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
float sum = 0, avg = 0;
float* end = arr + SIZE;

    for(float* fPtr = arr; fPtr < end; fPtr++)
        sum += *fPtr; 
    avg = sum / SIZE;

    cout << "The sum is " << sum << endl;
    cout << "The average is " << avg << endl;