我的C ++代码不起作用

时间:2013-11-26 16:37:02

标签: c++ turbo-c++

我是C ++编程的学生我正在尝试用c ++创建一个年龄计算器,但我坚持将变量与另一个变量相乘 这是代码:

#include <iostream.h>
#include <conio.h>
void main()
{
    clrscr();
    int birthmonth,birthyear,birthdate;
    int currentmonth,currentyear,currentdate;
    int year,month,weeks,cal,calx,days,hours;
    cout<<"Hassan's Age Calculator\n\n";
    cout<<"Enter Your Birth Year(i.e:1996):";
        cin>>birthyear;
    cout<<"\nEnter Your Birth Month(i.e:10):";
        cin>>birthmonth;
    cout<<"\nEnter date of Birth(i.e:27):";
        cin>>birthdate;
    cout<<"\nEnter The Current Month(i.e:7):";
        cin>>currentmonth;
    cout<<"\nEnter The Current Year(i.e:2013):";
        cin>>currentyear;
    cout<<"\nEnter Current Date(i.e:24):";
        cin>>currentdate;
    year=currentyear-birthyear;
    month=year*12;
    weeks=month*4.34;
    cal=(year*365.242)+currentdate;
    calx=cal+30.43;
    days=calx-birthdate;
    hours=days*24;

    cout<<"\n\n\t\tYour Age is "<<year<< " in Years" ;
    cout<<"\n\n\t\tYour Age is "<<month<< " in Months" ;
    cout<<"\n\n\t\tYour Age is "<<weeks<<" in weeks";           
    cout<<"\n\n\t\tYour Age is "<<days<<" in days";
    cout<<"\n\n\t\tYour Age is "<<hours<<" in hours";
    getch();
}

看到变量名称小时它不工作它显示18640但它应该是149712通过将变量(天)的答案乘以24,并且控制台屏幕上的天数为6238我正在使用turbo C 4.0 ++我需要帮助我做错了。

1 个答案:

答案 0 :(得分:13)

看起来你的史前编译器有16位int类型。 149712太大而不适合16位,因此计算溢出并给出不正确的值。你应该:

  • 如果您需要的类型保证足以表示高达数十亿的数字,请使用longint32_t;或者可能是floatdouble,因为你正在进行浮点运算;
  • 使用现代编译器。在该编译器的生命周期内,语言和标准库有两个主要更新,而您编写的语言几乎不可识别为C ++。