C 两次之间的时间差
C++ Time difference between two times
该程序的目的是计算开始时间和结束时间之间的时间差。
开始和结束时间将作为4位数字整数输入,并且需要计算时间差。输入的时间表示为HH:mm,没有":"。
Example:
first time: 0800
second time: 1755
Time elapsed: 9 hr and 55 min
这是我拥有的代码:
int main()
{
int first_time;
int second_time;
int dif_time;
double mod_time;
cout<<"Enter first time" << endl;
cin>>first_time;
cout<<"Enter second time" << endl;
cin>>second_time;
dif_time = second_time - first_time;
mod_time = dif_time % 60;
std::cout << "Time elapsed: " << dif_time << " hours" << mod_time << " minutes" << endl;
}
问题是它确实正确地输出了时间。关于如何改进该计划的任何建议将不胜感激。
最好在几分钟内转换所有内容,计算差异,然后转换为小时和分钟:
#include <iostream>
int main()
{
int first_time;
int second_time;
std::cout << "Enter first time" << std::endl;
std::cin >> first_time;
std::cout << "Enter second time" << std::endl;
std::cin >> second_time;
int first_time_min = first_time / 100 * 60 + first_time % 100;
int second_time_min = second_time / 100 * 60 + second_time % 100;
int diff_time_min = second_time_min - first_time_min;
std::cout << "Time elapsed: " << diff_time_min / 60 << " hours " << diff_time_min % 60 << " minutes" << std::endl;
}
可能的解决方案:
#include <iostream>
int main() {
int first_time;
int second_time;
int dif_time_in_minutes;
int hours, minutes;
std::cout << "Enter first time:";
std::cin >> first_time;
std::cout << "Enter second time:";
std::cin >> second_time;
dif_time_in_minutes = (second_time / 100)*60 + (second_time % 100) -
(first_time / 100) * 60 + (first_time % 100);
hours = dif_time_in_minutes / 60;
minutes = dif_time_in_minutes % 60;
std::cout << "Time elapsed: " << hours << " hours " << minutes << " minutes" << std::endl;
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- C 两次之间的时间差
- 为什么这两个实现多维数组之间会有如此巨大的执行时间差
- c++ 中的 clock() 时间和 java 中的 System.CurrentTimeMillis() 之间的时间差
- 两个语句执行之间的时间差不一致
- 时间差-两个时间点之间的差,以毫秒为单位
- 现在和现在之间的时间差为1小时(c++)