Время задается в формате час, минута, секунда. Реализовать:
1) вычитание из времени указанного пользователем количества секунд;
2) подсчёт числа секунд между двумя моментами времени, лежащими в пределах одних суток.
Вот пример работы программы:
Не помню уже, кто предоставил данное решение этой задачи, но ктобы это ни был — огромное ему/ей спасибо. Задачка не самая простая, но код получился хороший, удобочитаемый. Вот исходник программы:
#include <iostream>
#include <cassert>
using namespace std;
struct Time
{
int sec;
int min;
int hour;
};
Time inTime();
int main ()
{
Time myTime = inTime();
int numSec;
cout << "Введите количество секунд: ";
cin >> numSec;
assert(numSec >= 0);
int res = (myTime.sec + (myTime.min * 60) + (myTime.hour * 3600) - numSec); // перевод в секунды
myTime.hour = res / 3600;
myTime.min = (res %= 3600) / 60;
myTime.sec = res % 60;
cout << "Оставшееся время: " << myTime.hour << ":" <<myTime.min << ":" <<myTime.sec << endl;
cout << "Введите первый момент времени\n";
Time myTime1 = inTime();
cout << "Введите второй момент времени\n";
Time myTime2 = inTime();
int sec1 = (myTime1.sec + (myTime1.min * 60) + (myTime1.hour * 3600)),
sec2 = (myTime2.sec + (myTime2.min * 60) + (myTime2.hour * 3600));
if (sec1 > sec2)
sec1 -= sec2;
else
sec1 = sec2 - sec1;
cout << "Количество секунд между введенными моментами времени: " << sec1 << endl;
return 0;
}
// ввод времени
Time inTime()
{
Time t;
cout << "Введите значения времени!\n>> часы: ";
cin >> t.hour;
assert(t.hour >= 0 && t.hour <= 24);
cout << ">>минуты: ";
cin >> t.min;
assert(t.min >= 0 && t.min < 60);
cout << ">>секунды: ";
cin >> t.sec;
assert(t.sec >= 0 && t.sec < 60);
return t;
}
Смотрим результат работы программы:
CppStudio.com
Введите значения времени! >> часы: 4 >>минуты: 32 >>секунды: 47 Введите количество секунд: 145 Оставшееся время: 4:30:22 Введите первый момент времени Введите значения времени! >> часы: 12 >>минуты: 10 >>секунды: 12 Введите второй момент времени Введите значения времени! >> часы: 18 >>минуты: 45 >>секунды: 0 Количество секунд между введенными моментами времени: 23688
Комментарии
Роман Максимов
/* Время задается в формате час, минута, секунда. Реализовать: 1) вычитание из времени указанного пользователем количества секунд; 2) подсчет числа секунд между двумя моментами времени, лежащими в пределах одних суток; */ //--------------------------------------------------------------------------- #include <iostream> //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- class MyTime { int h, // часы m, // минуты s; // секунды unsigned int cnt_s; // время в секундах public: MyTime() { setTime(0); } MyTime(unsigned int seconds) { setTime(seconds); } MyTime(int hours, int minutes, int seconds) { setTime(hours, minutes, seconds); } ~MyTime(){}; // Время задается в привычном для человека виде void setTime(int hours, int minutes, int seconds); // Время задается в секундах void setTime(unsigned int seconds); // Получить значение времени в секундах int getTime(void) { return cnt_s; } // Отобразить время в привычном для человека виде void showTime(void); void operator=(MyTime t); MyTime operator-(MyTime t); MyTime operator-(unsigned int seconds); bool operator>(MyTime t); bool operator<(MyTime t); }; void MyTime::setTime(int hours, int minutes, int seconds) { h = hours; m = minutes; s = seconds; cnt_s = h * 3600 + m * 60 + s; } void MyTime::setTime(unsigned int seconds) { cnt_s = seconds; h = (int)(cnt_s * 0.000278) % 24; m = (int)(cnt_s * 0.0167) % 60; s = cnt_s % 60; } void MyTime::showTime(void) { cout << h << ':' << m << ':' << s << endl; } void MyTime::operator=(MyTime t) { this->h = t.h; this->m = t.m; this->s = t.s; this->cnt_s = t.cnt_s; } MyTime MyTime::operator-(MyTime t) { return MyTime(this->cnt_s - t.cnt_s); } MyTime MyTime::operator-(unsigned int seconds) { return MyTime(this->cnt_s - seconds); } bool MyTime::operator>(MyTime t) { return (this->cnt_s > t.cnt_s) ? true : false; } bool MyTime::operator<(MyTime t) { return (this->cnt_s < t.cnt_s) ? true : false; } //--------------------------------------------------------------------------- int main() { MyTime t, t1, t2; int h, m, s; cout << "Enter the time values!" << endl; cout << ">> hours: "; cin >> h; cout << ">> minutes: "; cin >> m; cout << ">> seconds: "; cin >> s; t1.setTime(h, m, s); cout << "Enter the number of seconds: "; cin >> s; t1 = t1 - s; cout << "Time left: "; t1.showTime(); cout << "Enter the time values!" << endl; cout << ">> hours: "; cin >> h; cout << ">> minutes: "; cin >> m; cout << ">> seconds: "; cin >> s; t1.setTime(h, m, s); cout << "Enter the second time" << endl; cout << "Enter the time values!" << endl; cout << ">> hours: "; cin >> h; cout << ">> minutes: "; cin >> m; cout << ">> seconds: "; cin >> s; t2.setTime(h, m, s); t = (t1 > t2) ? (t1 - t2) : (t2 - t1); cout << "The number of seconds between the entered time points: " << t.getTime() << endl; system("pause"); return 0; } //---------------------------------------------------------------------------Anufree
#include <iostream> #include <conio.h> using namespace std; void input_time(int &h, int &m, int &s) { do { cout << "\n\t\tчасы: \t"; cin >> h; if(h < 0 || h > 23) cout << "!!!УКАЗАН ЗАПРЕДЕЛЬНЫЙ ДИАПАЗОН (повторите ввод)" << endl; }while(!(h >= 0 && h < 24)); do { cout << "\t\tминуты: "; cin >> m; if(m < 0 || m > 59) cout << "!!!УКАЗАН ЗАПРЕДЕЛЬНЫЙ ДИАПАЗОН (повторите ввод)" << endl; }while(!(m >= 0 && m < 60)); do { cout << "\t\tсекунды:"; cin >> s; if(s < 0 || s > 59) cout << "!!!УКАЗАН ЗАПРЕДЕЛЬНЫЙ ДИАПАЗОН (повторите ввод)" << endl; }while(!(s >= 0 && s < 60)); } void sub_time(int &h, int &m, int &s) { int sec = 0, e_sec = 0, h_t, m_t; cout << "\n\n\t\tВведите колличество секунд: "; cin >> sec; e_sec = ((h * 3600) + (m * 60) + s); if(e_sec < sec) { h = 0; m = 0; s = 0; system("cls"); cout << "\t\t\tОСТАТОК ВРЕМЯНИ ПОСЛЕ ВЫЧИТАНИЯ: " << h <<':' << m << ':' << s << endl; return; }else { h = (e_sec - sec) / 3600; m = ((h * 3600) - (e_sec - sec)) / 60; if(m < 0) m *= -1; if(h > 0) { s = (((h * 3600) - (m * 60)) - (e_sec - sec)); }else { s = ((m * 60) - (e_sec - sec)); } if(s < 0) s *= -1; } system("cls"); cout << "\t\t\tОСТАТОК ВРЕМЯНИ ПОСЛЕ ВЫЧИТАНИЯ: " << h <<':' << m << ':' << s << endl; } void difference_time(int &h, int &m, int &s) { int h_t = 0, m_t = 0, s_t = 0; cout << "\n\n\t\t\tВведите второй момент времяни: " << endl; input_time(h_t, m_t, s_t); h -= h_t; if(h < 0) h *= -1; m -= m_t; if(m < 0) m *= -1; s -= s_t; if(s < 0) s *= -1; cout << "\n\t\t\tРазница между введенными моментами времени: " << (s + (m * 60) + (h * 3600)) << endl; } int main() { char a; int h = 0, m = 0, s = 0; setlocale(LC_ALL, "Russian"); cout << "\t\t\tТЕКУЩЕЕ ВРЕМЯ: " << h <<':' << m << ':' << s << endl; while(true) { cout << "\n\t\t\tМЕНЮ:" << endl; cout << "\n\t\tI Ввод времяни" << endl; cout << "\t\tS Вычитание от введенного времени (вычитается секундами)" << endl; cout << "\t\tC Подсчет колличиства секунд между двумя отрезками времени" << endl; cout << "\t\tQ Выход"; a = _getch(); switch(a) { case 'I' : case 'i' : cout << "\n\n\t\t\tВведите текущее время: " << endl; input_time(h, m, s); system("cls"); cout << "\t\t\tВВЕДЕННОЕ ВРЕМЯ: " << h <<':' << m << ':' << s << endl; break; case 'S' : case 's' : sub_time(h, m, s); break; case 'C' : case 'c' : difference_time(h, m, s); break; case 'Q' : case 'q' : exit(1); break; } } _getch(); return 0; }