我是编程新手,也是新手。 抱歉愚蠢的问题,但我的结果在我的“计算你的年龄秒”代码。它给了我奇怪的结果,如6.17725e + 10或-6.17414e + 10。 程序还没有完成,但除了结果之外的一切看起来都很好(我没有得到任何错误。 再次抱歉,我希望您的理解:)
#include <iostream>
using namespace std;
void title()
{
cout << "Age Calculator" << endl << endl;
}
int byear()
{
cout << "Enter your birth year: ";
int by;
cin >> by;
return by;
}
int bmonth()
{
cout << "Enter your birth month: ";
int bm;
cin >> bm;
return bm;
}
int bday()
{
cout << "Enter your birth day: ";
int bd;
cin >> bd;
return bd;
}
int cyear()
{
int cy;
cout << "Enter current year ";
cin >> cy;
return cy;
}
int cmonth()
{
cout << "Enter current month: ";
int cm;
cin >> cm;
return cm;
}
int cday()
{
cout << "Enter current day: ";
int cd;
cin >> cd;
return cd;
}
void calculate(int by, int bm, int bd, int cy)
{
double y = 31104000;
long double cby = y * by;
long double cbm = 259200 * bm;
long double cbd = 8640 * bd;
long double ccy = 31104000 * cy;
cout << endl << cby << endl;
cout << endl << ccy << endl;
cout << endl << ccy - cby << endl;
}
int main()
{
title();
int by = byear();
int bm = bmonth();
int bd = bday();
int cy = cyear();
int cm = cmonth();
int cd = cday();
calculate(by, bm, bd, cy);
cin.get();
return 0;
}
答案 0 :(得分:0)
cout.precision(your_precision_here)
更改cout的精确度。请参阅下面的问题。
How do I print a double value with full precision using cout?
答案 1 :(得分:0)
首先,您感到困惑的数字格式是“科学记数法”。这将是打开谷歌搜索世界的足够信息,或者你可以强制它不以科学记数法打印。
其次,你真的想要为任何日历内容使用时间库。它将为您处理各种日历怪异,包括闰年。幸运的是我们有time.h
第三,我建议使用整数类型秒,部分是为了避免舍入错误和丑陋的小数,但主要是因为这是time.h使用的。只要确保它足够大。我的编译器对time_t使用64位整数,所以我使用了:
#include <time.h>
#include <memory>
time_t get_age_in_seconds(int year, int month, int day)
{
struct tm birthday;
memset(&birthday, 0, sizeof(birthday));
birthday.tm_year = year - 1900; // years since 1900
birthday.tm_mon = month - 1; // months since January (0,11)
birthday.tm_mday = day; // day of the month (1,31)
time_t birthday_in_seconds = mktime(&birthday);
time_t now = time(NULL);
return now - birthday_in_seconds;
}
答案 2 :(得分:0)
不要使用双打进行计算。由于您没有进行任何除法,因此您不会有任何小数值。
更重要的是,请查看mktime()
,time()
和difftime()
。您应该使用它们来进行计算。