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.
return (numbers.empty() ? -1. : (std::accumulate(numbers.begin(), numbers.end(), 0.) / numbers.size());.int i=0,result = 0declares twointvariables. It's not one declaration with initializer and one assignment, separated by the comma operator.