c++ - 将分钟转换为天、小时、分钟和秒

标签 c++

我在初学者级别的 C++ 类(class)中,当我在 C++ 中将分钟转换为天、小时、分钟和秒时,我无法弄清楚为什么我得到错误的输出。

我有一个 friend 帮助我,她能够使用相同的数学在 Python 中获得正确的输出,但由于某些原因在 C++ 中我无法在几秒钟内获得正确的输出。我确信有一种更简单的方法来获取输出,但这就是教授希望我们编写的方式。

例如,输入为 10.5,代码输出 0d 0h 10m 0s 而不是 0d 0h 10m 30s。

代码如下:

#include <iostream>
using namespace std;

int main() {

  //get the starting number of minutes
  int inputMinutes;
  double decimalMinutes;
  cout << "Enter number of minutes: ";
  cin >> decimalMinutes;

    //allow decimal input
    inputMinutes = decimalMinutes;

    //get number of days
    int days = inputMinutes / 1440;
    inputMinutes = inputMinutes % 1440; 

    //get number of hours 
    int hours = inputMinutes / 60;

    //get number of minutes 
    int mins = inputMinutes % 60;

    int seconds = inputMinutes % 1 * 60;

    //output days, hours, minutes and seconds
    cout << days << "d " << hours << "h " << mins << "m " << seconds << "s" << endl;
}

我觉得这与将 int 转换为 double 有关,但如果不是这种情况,那么我不确定它可能有什么问题。感谢任何帮助,谢谢。

最佳答案

正如其他用户已经指出的那样,当您编写 inputMinutes = decimalMinutes; 时,您将 double 转换为 int,丢失了所有信息关于小数部分。您必须将这部分与 decimalMinutes 变量的整数部分分开,然后将其乘以 60 以获得秒数。请参见下面的代码。

#include <iostream>

int main() {

  //get the starting number of minutes
  int inputMinutes;
  double decimalMinutes;
  double decPart;
  std::cout << "Enter number of minutes: ";
  std::cin >> decimalMinutes;

    //allow decimal input
    inputMinutes = decimalMinutes;
    decPart = decimalMinutes-inputMinutes;


    //get number of days
    int days = inputMinutes / 1440;
    inputMinutes = inputMinutes % 1440; 

    //get number of hours 
    int hours = inputMinutes / 60;

    //get number of minutes 
    int mins = inputMinutes % 60;

    int seconds = decPart * 60;

    //output days, hours, minutes and seconds
    std::cout << days << "d " << hours << "h " << mins << "m " << seconds << "s" << std::endl;

    return 0;
}

这应该有效:这些是我的一些输出。

Enter number of minutes: 10.5
0d 0h 10m 30s

Enter number of minutes: 126.3333333
0d 2h 6m 19s

Enter number of minutes: 1440.4
1d 0h 0m 24s

Enter number of minutes: 12.1
0d 0h 12m 5s

你看到还有一些舍入问题(如果你想计算 1/3 分钟你应该输入周期数 0.333333333...,而 0.1 的表示在浮点运算中是周期性的)这是由于如何处理从 doubleint 的转换(请参阅@PaulMcKenzie 对您的回答的评论)。

关于c++ - 将分钟转换为天、小时、分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63729721/

相关文章:

c++ - 使用 Boost 时的内存泄漏检测

c++ - 如何在linux上使用mingw编译glog生成glog dll

c++ - 比较C中的两个int数组

c++ - clang-format 打破 lint 注释

c++ - 支持非标准波特率的 Boost::Asio::SerialPort 替代方案?

c++ - GDCM:我想对图像做一个简单的锐化过滤器,但不知道如何改变像素值

android - JNI - 在 NewObjectArray 上崩溃

c++ - 在析构函数和后续析构函数中引发异常

c++ - 是否可以像容器一样在堆栈中创建非递归析构函数?

C++ 使用单词列表作为分隔符拆分字符串