dimanche 1 avril 2018

Double/Integer use and data narrowing within a Range-Based for loop

I am working my way through Bjarne Stroustrup's Programming Principles and Practice and am having difficulty. I am currently reading on Vectors and have been introduced to Range-based for loops. Below I have some code, that from my eyes, appears to be reading a double into an INT; which I assume causes narrowing.

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';
    keep_window_open();
    return 0;
}

Upon trying this a few times with different inputs I have arrived at the conclusion this is indeed narrowing. I am creating a vector of doubles and than in the for(int x : temps) loop, taking the first element within temp, putting it within x, processing it than incrementing to the next element and repeating. Because the element (a double) is being read into x (an integer) causing the narrowing.

My main question is if I am indeed correct it is narrowing the elements within the vector (maybe it doesn't actually read into x and that int x is describing something else), can I simply replace for(int x : temps) to for(double x : temps) to avoid this narrowing, or is the use of an integer in the range-based for loop parameters mandatory (maybe designed that way). Any thoughts, thanks.

Aucun commentaire:

Enregistrer un commentaire