Home > Blockchain >  multiple initializations in for loop
multiple initializations in for loop

Time:01-27

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.

CodePudding user response:

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.

  •  Tags:  
  • Related