如何让C++程序在输入日期无效时停止执行后续运算判断语句
问题核心原因
你的代码将「日期合法性校验」和「日期信息、闰年结果输出」设为了完全独立的两段逻辑,无论日期是否合法,后续的输出逻辑都会强制执行,才会出现无效日期同时输出报错和闰年判断的问题。
修复步骤
- 新增一个布尔类型的合法性标记,初始值为
true,用于记录日期是否通过校验 - 所有触发错误提示的分支中,将标记值改为
false - 将「打印月份全称」「判断闰年输出」的两段代码,全部包裹在合法性标记为
true的判断分支中,只有日期合法时才执行 - 顺便修正原有代码的两处逻辑bug:
- 原2月29日合法性判断中的
year%400 == 400为错误逻辑,应修改为「不是闰年」的判断条件 - 原闰年判断中
year%400==0的分支为空,没有输出对应闰年提示
- 原2月29日合法性判断中的
修正后完整代码
#include <iostream> using namespace std; int main() { int month, day, year; cout<<"Enter numeric values for the current date [mm dd yyyy] ->"; cin>>month>>day>>year; // 新增合法性标记 bool is_date_valid = true; if (month > 12 || month < 1){ cout<<"The month must be in the interval [1,12]. "<<endl; is_date_valid = false; } else if (day > 31 || day < 1){ cout<<"The day must be in interval [1,31]. "<<endl; is_date_valid = false; } else if (year < 1582){ cout<<"The year must come after 1582. "<<endl; is_date_valid = false; } else if (month == 2 && day > 29){ cout<<"The day in February cannot be greater than 29. "<<endl; is_date_valid = false; } // 修正此处闰年判断逻辑 else if (month == 2 && day == 29 && !(year%400==0 || (year%4 == 0 && year%100 !=0))){ cout<<"February cannot have 29 days in a common year. "<<endl; is_date_valid = false; } else if (month == 4 && day == 31){ cout<<"The day in April cannot be 31. "<<endl; is_date_valid = false; } else if (month == 6 && day == 31){ cout<<"The day in June cannot be 31. "<<endl; is_date_valid = false; } else if (month == 9 && day == 31){ cout<<"The day in September cannot be 31. "<<endl; is_date_valid = false; } else if (month == 11 && day == 31){ cout<<"The day in November cannot be 31. "<<endl; is_date_valid = false; } // 只有合法日期才执行后续输出 if (is_date_valid) { if (month==1){ cout<<"The date January "<<day<<", "<<year; } else if (month==2){ cout<<"The date February "<<day<<", "<<year; } else if (month==3){ cout<<"The date March "<<day<<", "<<year; } else if (month==4){ cout<<"The date April "<<day<<", "<<year; } else if (month==5){ cout<<"The date May "<<day<<", "<<year; } else if (month==6){ cout<<"The date June "<<day<<", "<<year; } else if (month==7){ cout<<"The date July "<<day<<", "<<year; } else if (month ==8){ cout<<"The date August "<<day<<", "<<year; } else if (month == 9){ cout<<"The date September "<<day<<", "<<year; } else if (month==10){ cout<<"The date October "<<day<<", "<<year; } else if (month == 11){ cout<<"The date November "<<day<<", "<<year; } else if (month == 12) { cout<<"The date December "<<day<<", "<<year; } // 修正此处闰年判断的空分支问题 if (year%400==0 || (year%4 == 0 && year%100 !=0)){ cout<<" is in a leap year."<<endl; } else { cout<<" is in a common year."<< endl; } } return 0; }
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

