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;

    }
8
  • 3
    why sum is an int? it makes more sense for it to be float. And you are using average without initialization. Commented Nov 7, 2016 at 23:32
  • That's the part I dont understand what to do ? Because of the converting. Cheers. Commented Nov 7, 2016 at 23:33
  • ints may have a different size from float which would make end pretty messed up Commented Nov 7, 2016 at 23:33
  • is that C or C++? Commented Nov 7, 2016 at 23:34
  • I suppose OP could have some complicated macro nonsense to make cout << work in C, @Raindrop7 Commented Nov 7, 2016 at 23:35

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, although this does work, I can't use an integer index.
Works like a charm, Thank you so much. I am so glad to join this wonderful website.
@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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.