c++ - 以秒为单位计算年龄的程序无法正常工作

标签 c++

我正在尝试创建一个简单的程序,在用户以年为单位计算年龄后,以秒为单位计算用户年龄。它适用于 0-68 岁的人群,但任何 69 岁或以上的人群都会破坏该程序,并且每次都会吐出相同的错误数字。该程序如下所列,如有任何帮助,我们将不胜感激。

#include <iostream>
using namespace std;


int main()
{
    int age;

    cout << "Please enter your age in years ";
    cin  >> age; //Grabs the users age
    unsigned long long int result = age*365*24*60*60; //calculates the users age in seconds
    cout << "Your age in seconds is: " << result << " seconds";
    return 0;
}

最佳答案

C++ 在这里的工作方式基本上是:

int temp = age*365*24*60*60;
unsigned long long int result = static_cast<unsigned long long>(temp);

因此,您可能会看到表达式将在 69 岁左右(在您的架构上)溢出 int。所以,你想强制计算在 unsigned long long 中工作,所以最简单的方法是强制其中一个值是 unsigned long long,这将使表达式也 unsigned long long。例如:

unsigned long long int result = age*365ULL*24*60*60; //calculates the users age in seconds
//                                     ^^^ declare constant as type unsigned long long

关于c++ - 以秒为单位计算年龄的程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42196056/

相关文章:

c++ - select() 和 FD_ISSET() 成功后 read() 失败

c++ - 重载运算符帮助?

c++ - QNetworkReply::NetworkError(ProtocolInvalidOperationError) 它是什么以及如何修复它?

C++ cout 副作用排序

c++ - 如何从客户端代码中隐藏模板化的非成员函数?

c++ - 在具有多重继承的类构造函数中传递什么?

c# - 如何将非成员函数的地址存储在 DWORD 中 (c++)

c++: cin.clear() 不重置流

c++ - 模板化类和处理不需要的类型声明的良好实践

c++ - 什么适用于 C++ 中的 Web 开发