debugging 基于负数的代码错误,需要时间计算器的可能修复,需要关于我应该在哪里添加一天的额外分钟的帮助

c90pui9n  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(137)

嗨,我用C++创建了一个程序,(我也是个新手)。这个程序基本上要求使用两个时间,比如3:57和持续时间1:05,它会告诉你两者之间的和和差。问题是我得到了负余数,比如如果我输入1:18和10:39,我期望11:57和2:39,但当我运行程序时,我得到的结果是11:57和-9:-21。我该怎么办?这是一个赋值语句,我们不能使用if语句。说明说,如果我们有这个问题,我们应该“这很容易做到,通过增加一天(或两三天)之前计算差异。”我不知道这意味着什么,一直在这方面挣扎。我通过了大多数测试,除了当时间去负代码如下:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int run()
{



    cout << "Give me a time (such as 3:57) and a duration" << endl;
    cout << "(such  1:05), and  will tell you the sum" << endl;
    cout << "(that is the time that follows the given time" << endl;
    cout << "by the given duration), and difference (the time that proceeds the given time by that duration)."  << endl;

    cout << "Time: " << endl;
    int timeHours;
    int timeMinutes;
    char discard;

    cin >>  timeHours >> discard >> timeMinutes;

    cout <<"Duration: " << endl;
    int durationHours;
    int durationMinutes;

    cin >> durationHours >> discard >> durationMinutes;


int time = timeHours * 60 + timeMinutes;
 int duration = durationHours * 60 + durationMinutes;
 int after = time + duration;
 int before = time - duration ;
 int afterHours = after / 60 % 12  ;
 int afterMinutes = after % 60;
 int beforeHours = before  / 60 ;
 int beforeMinutes = before % 60;


cout << endl;
 cout << durationHours <<":" << durationMinutes << " hours after and before, "
 << timeHours << ":"  <<timeMinutes << " is ["  << afterHours   << ":" << setw(2) << 
setfill('0')<< afterMinutes <<", "
 << beforeHours << ":" << beforeMinutes << "]" << endl;
return(0);
}

任何帮助,使这个程序正常工作是非常感谢。我是新的C++和非常沮丧。

aij0ehis

aij0ehis1#

给您:

int after = time + duration;
 if(time - duration < 0) time += 1440;
 int before = time - duration;
 int afterHours = after / 60 % 12;

P.S.很抱歉代码块不直观,我是新来的。

相关问题