任務是比較兩個資料。例如,輸出是:第一個日期在第二個日期之前。我只能用 if-else 來解決這個問題。我的問題是忽略了其他 else-if 條件,因為第一個條件可能為真。我該如何解決?日期不是一起輸入的,而是單獨作為整數輸入的。
int D;
int M;
int Y;
int D2;
int M2;
int Y2;
cout << "Please enter the day of the first date:";
cin >> D;
cout << endl;
cout << "Please enter the month of the first date";
cin >> M;
cout << endl;
cout << "Please enter the year of the first date";
cin >> Y;
cout << endl;
cout << "Please enter the day of the second date";
cin >> D2;
cout << endl;
cout << "Please enter the month of the second date";
cin >> M2;
cout << endl;
cout << "Please enter the year of the second date";
cin >> Y2;
cout << endl;
if (D == D2 && M == M1 && Y == Y2)
{
cout << "Both dates are the same" << endl;
}
else if (Y2 >= Y)
{
cout << "The first date is before the second date" << endl;
}
else if (Y >= Y2)
{
cout << "The second date is before the first date" << endl;
}
else if (D2 >= D)
{
cout << "The first date is before the second date" << endl;
}
else if (D >= D2)
{
cout << "The second date is before the first date" << endl;
}
else if (M2 >= M)
{
cout << "The first date is before the second date" << endl;
}
else if (M >= M2)
{
cout << "The second date is before the first date" << endl;
}
uj5u.com熱心網友回復:
你有一些邏輯問題,你需要重組你的if-else:
if (Y2 > Y)
cout << "date 2 after date 1" << endl;
else if (Y2 < Y)
cout << "date 2 before date 1" << endl;
else {
// here we know that Y2 == Y, so we need to continue with month/day
if (M2 > M)
cout << "date 2 after date 1" << endl;
else if (M2 < M)
cout << "date 2 before date 1" << endl;
else {
// here we know that Y2 == Y AND M2 == M, so we need to continue with day
... here you can continue
}
}
uj5u.com熱心網友回復:
問題是,當您使用時else if,一旦某事為真,您就會忽略所有內容。修復很簡單,只要去掉elses,如果你保留它們,當某些事情為真時,下面的所有代碼都將被忽略。此外,我強烈建議您使用 for 回圈來使您的代碼更有條理。
有關條件的更多資訊,我建議您閱讀:https ://www.w3schools.com/c/c_conditions.php
uj5u.com熱心網友回復:
我會結合每個日期的資訊:
// Yes, the multipliers look peculiar; this allows for
// 1-based data ranges. Of course, this calculation should
// be done in its own function.
unsigned long long date0 = (Y * 13ULL M) * 32 D;
unsigned long long date2 = (Y2 * 13ULL M2) * 32 D2;
if (date0 < date2)
std::cout << "The first date is before the second date\n";
else if (date0 == date2)
std::cout << "Both dates are the same.\n";
else
std::cout << "The second date is before the first date\n";
對于直接的蠻力代碼,您只想得到三個可能的輸出陳述句;不要多次寫入相同的輸出。這意味著您必須仔細研究獲得其中一項輸出的所有可能方式。
如果第一年小于第二年,或者如果兩年相同并且第一個月在第二個之前,或者如果兩年相同并且兩個月是,則第一個日期在第二個日期之前同樣的,第一天在第二天之前。如果所有三個值都相同,則第一個日期與第二個日期相同。如果前兩種情況都不成立,則第二個日期在第一個日期之前。
現在只需撰寫代碼即可。這是一個開始:
if (Y < Y2
|| Y == Y2 && M < M2
|| /* left as an exercise for the student */)
std::cout << "The first date is before the second date\n";
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517960.html
上一篇:根據if陳述句更改頁面的屬性
下一篇:優化if陳述句中的條件
