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

 usx7054252 发布于 2023-02-12 13:50

该程序应该存储自午夜以来的秒数,并以标准和通用时间显示.它运行,但设置的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 <

主程序:

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: "<>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();
}

Tim Seguine.. 5

在您的打印功能中,您有一个与您的字段同名的本地变量secondsSinceMidnight.它正在遮蔽它.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有