[英]Error in code based off negative numbers. Need possible fix on time calculator. Need help on where i should add the additional minutes of the day
Hi I have created a program in C++, (which I am very new too).嗨,我在 C++ 中创建了一个程序(我也很新)。 This program basically asks the used for two times such as 3:57 and the duration 1:05 and it will tell you the sum and the difference between the two.
该程序基本上会询问两次使用的时间,例如 3:57 和持续时间 1:05,它会告诉您两者的总和和差异。 The problem is I am getting negative remainders such as if I put an input of 1:18 and 10:39 I expect 11:57 and 2:39 but I get 11:57 and -9:-21 as result when I run the program.
问题是我得到了负余数,例如如果我输入 1:18 和 10:39 我期望 11:57 和 2:39 但是当我运行时我得到 11:57 和 -9:-21程序。 What should I do?
我应该怎么办? This is for an assignment and we cannot use if statements.
这是一个赋值,我们不能使用 if 语句。 The instructions say if we are having this problem we should " This is easily done by adding a day (or two or three) to before when calculating the difference."
说明说如果我们遇到这个问题,我们应该“这很容易通过在计算差异时在之前添加一天(或两三天)来完成。” I do not know what this means and have been struggling on this.
我不知道这意味着什么,并且一直在为此苦苦挣扎。 i pass most tests besides when the time goes negative code is below:
我通过了大多数测试,除了时间到负代码如下:
#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);
}
Any help to make this program work properly is greatly appreciated.非常感谢任何使该程序正常工作的帮助。 I am new to C++ and very frustrated.
我是 C++ 的新手,非常沮丧。
Here you go:这里是 go:
int after = time + duration;
if(time - duration < 0) time += 1440;
int before = time - duration;
int afterHours = after / 60 % 12;
Ps Sorry about non-intuitive code block, I'm new around here. Ps 对不直观的代码块感到抱歉,我是新来的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.