0

I am trying to write a function to find the average of numbers at first i wrote code as

double CPPLib::average_of_numbers(std::vector<int> &numbers){
    double result = -1;
    if(numbers.size() != 0)
    {
        result = 0;
        for(int i=0;i< int(numbers.size());i++)
        {
            result += numbers[i];
            std::cout << result << std::endl;
        }
        std::cout << result << std::endl;
        result = result/numbers.size();
        std::cout << result << std::endl;
    }
    return result;
}

for the input {1,2,3,4,5} the above code works fine and prints 1 3 6 10 15 15 3 3 .but when i tried to include the result = 0 in "for" loop initialization i am getting result as -1 after for loop.as shown in the code

double CPPLib::average_of_numbers(std::vector<int> &numbers){
    double result = -1;
    if(numbers.size() != 0)
    {
        
        for(int i=0,result = 0;i< int(numbers.size());i++)
        {
            result += numbers[i];
            std::cout << result << std::endl;
        }
        std::cout << result << std::endl;
        result = result/numbers.size();
        std::cout << result << std::endl;
    }
    return result;
}

result is displayed as 1 3 6 10 15 -1 -0.2 -0.2 can you please let me know the reason for this. Thank you so much.

2
  • return (numbers.empty() ? -1. : (std::accumulate(numbers.begin(), numbers.end(), 0.) / numbers.size());. Commented Jan 27, 2022 at 10:43
  • Like everywhere else int i=0,result = 0 declares two int variables. It's not one declaration with initializer and one assignment, separated by the comma operator. Commented Jan 27, 2022 at 10:45

1 Answer 1

4

In your second example, you've actually declared two separate variables called result. The first is here at the top of your function.

double result = -1;

The other is here:

    for(int i=0,result = 0;i< int(numbers.size());i++)

You've declared both a temporary int named result (in addition to i) who's lifetime and scope is within the for-loop. It overrides the outer result declared earlier. When the for-loop exits, references to result are back to the original variable declared earlier.

Easiest fix is to do what you were doing in your first example. Explicitly set result=0 outside the loop.

Sign up to request clarification or add additional context in comments.

Comments

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.