【发布时间】:2016-02-18 04:01:48
【问题描述】:
我的逻辑在计算用户输入的两次之间的时间差时是错误的。
答案并没有得到应有的结果,我无法完全弄清楚我的逻辑哪里错了。我去找我的助教,她对我没有帮助。任何帮助将不胜感激。如果需要,我也会发布我的 main() 函数。因为我相信我的布尔值变得混乱了。
我正在尝试从主函数导入我的变量值并计算用户输入中有多少分钟,即第一个值是上午 2:10 = 130 分钟,第二个值是上午 2:20 即 = 140 , 输入之间有 10 分钟的差异。程序打印 138 分钟...如果有人能指出我积极的方向,将不胜感激。
int computeDifference(int hours, int minutes, int hourFut, int minFut, bool isAM, bool isAMFut){
cout<<isAM<<isAMFut<<endl;
int startTime, endTime;
startTime = calcHours(isAM, hourFut, minFut, isAMFut);
endTime = calcFut(hourFut, minFut, isAMFut, isAM);
diff = startTime - endTime;
if (diff < 0)
diff = abs(diff);
return diff;
}
int calcHours(int hours, int minutes, bool isAM, bool isAMFut){
if ((hours < 12) && (isAM))
return minutes +(hours * 60);
if ((hours == 12 && isAM))
hours = 0;
if(hours < 12 && !isAM)
return minutes + hours * 60;
}
int calcFut(int hourFut, int minFut, bool isAMFut, bool isAM){
if ((hourFut == 12) && isAM)
hourFut = 0;
if ((hourFut) < 12 && !isAM)
return minFut + hourFut * 60;
if ((hourFut < 12) && isAM)
return minFut + hourFut * 60;
}
**编辑主要功能
int main(){
//Declarations
int hours, minutes, hourFut, minFut;
bool isAM, isAMFut;
string amOrPM, amOrPMFut;
//Reading in the data from user
cout<<"Please enter the time (hours minutes) ";
cin>>hours>>minutes;
cout<<endl;
cout<<"Please enter PM or AM"<<endl;
cin>>amOrPM;
//Converting string to all uppercase so it is easier to check
transform(amOrPM.begin(), amOrPM.end(), amOrPM.begin(), ::toupper);
//Checks if user entered am, or pm if not asks them to re-enter
while ((amOrPM != "AM") && (amOrPM != "PM")){
cout<<"Please enter PM or AM: ";
transform(amOrPM.begin(), amOrPM.end(), amOrPM.begin(), ::toupper);
}
//Turns the boolean to true if it is the morning
if (amOrPM == "AM")
isAM = true;
else
isAM = false;
cout<<"It is currently "<<hours<<":"<<minutes<<amOrPM<<endl;
cout<<endl;
cout<<"When would you like to travel too?"<<endl;
//Reading in future time
cout<<"Please enter a time (hours minutes)"<<endl;
cout<<"Please enter a time (hours minutes)"<<endl;
cin>>hourFut>>minFut;
cout<<"Is it AM or PM?"<<endl;
cin>>amOrPMFut;
transform(amOrPMFut.begin(), amOrPMFut.end(), amOrPMFut.begin(), ::toupper);
//Checking if user enters am or pm
while ((amOrPMFut != "AM") && (amOrPMFut != "PM")){
cout<<"Is it AM or PM?"<<endl;
cin>>amOrPMFut;
transform(amOrPMFut.begin(), amOrPMFut.end(), amOrPMFut.begin(), ::toupper);
}
if (amOrPMFut == "AM")
isAMFut = true;
else
isAMFut = false;
cout<<isAM<<endl;
cout<<isAMFut<<endl;
【问题讨论】:
-
插入您期望的主要功能,标准输入和输出。我没有看到您需要两个函数来将时间转换为分钟的原因。
-
@AchmadJP 我添加了 main() 函数..
-
@AchmadJP 我要求用户输入两次,然后我想以分钟为单位计算两次的差异。
-
就像我说的,您只需将小时:分钟转换为总分钟数。为什么您甚至需要 2 个功能相同的功能?请添加完整的主程序,以便我可以在我自己的电脑上测试它。
-
@AchmadJP 整个程序已发布,减去 #include
、 、 和