https://rentry.org/PPP2_p156

// Code derived from Stroustrup's PPP2 book
// § 5.7 Logic errors
//  -and beginning on p 156

#include <iostream>

using std::cin;
using std::cout;

int main()
{
  cout << "Please enter temperatures: (enter '|' to stop):\n";

  double sum         = 0;
  double high_temp   = -1000;  // initialize to impossibly low
  double low_temp    = 1000;   // initialize to “impossibly high”
  int    no_of_temps = 0;

  for (double temp; cin >> temp;) {  // read a temp
    ++no_of_temps;                   // count temperatures
    sum += temp;                     // compute sum

    if (temp > high_temp)  // record high
      high_temp = temp;    //
                           //
    if (temp < low_temp)   // record low
      low_temp = temp;     //
  }

  cout << "High temperature: " << high_temp << '\n';
  cout << "Low temperature: " << low_temp << '\n';
  cout << "Average temperature: " << sum / no_of_temps << '\n';
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_05/main_p156.cpp && ./a.out

PrevUpNext

Edit
Pub: 24 Feb 2023 11:54 UTC
Edit: 29 Apr 2023 09:51 UTC
Views: 566