简体   繁体   中英

multiple initializations in for loop

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.

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, reference 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.

I have not tested yet but I assume it might be because of the fact that you are trying to add an "int" to a "double" which might give an incorrect answer. Don't forget that double and int are not of the same type.

Try changing result to int.

Also, there is no point in initializing result to -1 if you need to change it to 0 inside your if statement. Just initialize it to 0 and use it if the condition is valid.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM