我正在尝试创建一个简单的程序,在用户以年为单位计算年龄后,以秒为单位计算用户年龄。它适用于 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/