0

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;

    }
Chris Ashkar
  • 9
  • 1
  • 8

1 Answers1

1

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;
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • Thank you for your answer, although this does work, I can't use an integer index. – Chris Ashkar Nov 07 '16 at 23:43
  • Works like a charm, Thank you so much. I am so glad to join this wonderful website. – Chris Ashkar Nov 07 '16 at 23:52
  • @ChrisAshkar Remember: the very bad thing you were trying to do: "converting a pointer to float into an integer and inside the loop you are taking the value of this pointer to integer!! so any all the decimal part of array elements will be discarded" – Raindrop7 Nov 07 '16 at 23:57