在c++中修改时间程序时出现逻辑错误



这个程序应该以秒为单位存储午夜后的时间,并以标准时间和通用时间显示。它正在运行,但set Time函数中有一个错误,因为时间永远不会改变。我假设某些东西没有正确返回,但我找不到错误。

头文件:

#ifndef TIME_H
#define TIME_H
class Time
{
public:
    Time(); //constructor
    void setTime(int, int, int );
    void printUniversal(); //print time in universal-time format
    void printStandard(); // print time in standard-time format
private:
    int secondsSinceMidnight;
};
#endif 

.cpp文件

Time::Time()//constructor
{
    secondsSinceMidnight = 0;
}
void Time::setTime(int h, int m, int s)
{
    if ((h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0) && (s < 60))
    {
        int hoursInSecs = (h * 3600);
        int minutesInSecs = (m * 60);
        secondsSinceMidnight = (minutesInSecs + hoursInSecs);
    }
    else
        throw invalid_argument(
            "hour, minute and/or second was out of range");
}
void Time::printUniversal()
{
    int secondsSinceMidnight = 0;
    int hours = (secondsSinceMidnight / 3600);
    int remainder = (secondsSinceMidnight % 3600);
    int minutes = (remainder / 60);
    int seconds = (remainder % 60);
    cout <<setfill('0')<<setw(2)<<hours<<":"
    <<setw(2)<<minutes<<":"<<setw(2)<<seconds<<endl;
}
void Time::printStandard()
{
    int secondsSinceMidnight = 0;
    int hours = (secondsSinceMidnight / 3600);
    int remainder = (secondsSinceMidnight % 3600);
    int minutes = (remainder / 60);
    int seconds = (remainder % 60);
    cout<<((hours == 0 || hours == 12) ? 12 : hours % 12) << ":"
        << setfill('0') <<setw(2)<<minutes<< ":"<<setw(2)
        <<seconds<<(hours < 12 ? "AM" : "PM")<<"n"; 
}

主程序:

int main()
{
    Time t; //instantiate object t of class Time
    //output Time object t's initial values
    cout<<"The initial universal time is ";
    t.printUniversal();
    cout<<"nThe initial standard time is ";
    t.printStandard();
    int h;
    int m;
    int s;
    cout<<"nEnter the hours, minutes and seconds to reset the time: "<<endl;
    cin>>h>>m>>s;
    t.setTime(h, m, s); //change time

    //output Time object t's new values
    cout<<"nnUniversal time after setTime is ";
    t.printUniversal();
    cout<<"nStandard time after setTime is ";
    t.printStandard();
}

在打印函数中,您有一个与字段secondsSinceMidnight同名的局部变量。它正在跟踪它。

为什么int秒自午夜起=0;在printUniversal()和printStandard()的开头,这个变量将覆盖成员变量。

在两个打印函数的开头,都设置了secondsSinceMidnight = 0。将其保留在构造函数中,但将其从打印函数中删除。

最新更新