I'm in the process of learning c++. I've come across an assignment about temperatures I don't understand. Could you guys clarify some things for me?
Here's the code
// compute mean and median temperatures
int main()
{
vector<double> temps; // temperatures
for (double temp; cin>>temp; ) // read into temp
temps.push_back(temp); // put temp into vector
**// compute mean temperature:
double sum = 0;
for (int x : temps) sum += x;
cout << "Average temperature: " << sum/temps.size() << '\n';**
// compute median temperature:
sort(temps); // sort temperatures
cout << "Median temperature: " << temps[temps.size()/2] << '\n';
}
Now the second block (//compute mean temperature) is the stuff I cannot follow.
First off, a for-statement is used with a single argument. Won't this mean that there is just an initial expression and no condition?
I also don't think I have a firm understanding of int X : temps
int X isn't defined anywhere else in this bit of code. Won't it cause an error as it has no value assigned to it? Let's say it has a value of 1; what does it do/what does it check? Does it check how many times X fits in vector temps? Why not do this then:
int sum_of_measurements = 0; //value of all measurements
for (int y = 0; y <= temps.size(); ++y){
sum_of_measurements = sum_of_measurements + temps[y]; // add value of measurement to the total for each measurement
}
double mean = sum_of_measurements/temps.size();
cout << mean <<'\n';
//rest of code
What's this identifier called so I can learn more about it (the :
in int X : temps
)
Thanks :)