C++ std::round
Round an estimate to the nearest whole minute before showing it to a customer.
A simple example
std::round
- Start with 2.6
- Do this Round to the nearest integer
- Result 3
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::round(2.6)) << '\n';
}
3
Syntax
std::round(minutes)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonDisplay a delivery estimate in minutes
A courier predicts a delivery time with a fractional minute. Round the estimate for a whole-minute display and examine what happens when the prediction falls exactly between two displayed minutes.
#include <cmath>
#include <cstdio>
int main() {
const double minutes = 12.6;
std::printf("%.3f\n", std::round(minutes));
return 0;
}
13.000
Twelve minutes and six tenths is nearer thirteen than twelve.
Show a bus arrival on a station board
A transit or delivery display has room only for whole minutes. Convert a fractional estimate for display while keeping the more precise original estimate available to the scheduler.
#include <cmath>
#include <cstdio>
int main() {
const double minutes = 7.8;
std::printf("%.3f\n", std::round(minutes));
return 0;
}
8.000
A 7.8-minute prediction displays as eight minutes. Keep the full estimate for scheduling calculations.
Round a parcel reading for a whole-unit display
A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.
The reading lies closer to nineteen than eighteen.
What to watch for
std::round rounds exact half values away from zero, so -2.5 becomes -3.