gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:27 24 4
gpt4 key购买 nike

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

头文件:

#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<<"\n\nUniversal time after setTime is ";
t.printUniversal();
cout<<"\nStandard time after setTime is ";
t.printStandard();
}

最佳答案

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

关于c++ - 在c++中修改时间程序时出现逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20427359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com