在编程时,为了避免深度嵌套的if-else结构,可以使用以下几种格式:
多分支格式
```c
include int main() { int year, leap; printf("输入年份:"); scanf("%d", &year); if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { leap = 1; } else { leap = 0; } if (leap) { printf("%d是闰年\n", year); } else { printf("%d不是闰年\n", year); } return 0; } ``` ```c include int main() { int year; printf("输入年份:"); scanf("%d", &year); switch (year % 4) { case 0: if (year % 100 == 0) { if (year % 400 == 0) { printf("%d是闰年\n", year); } else { printf("%d不是闰年\n", year); } } else { printf("%d是闰年\n", year); } break; default: printf("%d不是闰年\n", year); break; } return 0; } ``` ```c include int is_leap_year(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return 1; } else { return 0; } } int main() { int year; printf("输入年份:"); scanf("%d", &year); if (is_leap_year(year)) { printf("%d是闰年\n", year); } else { printf("%d不是闰年\n", year); } return 0; } ``` 这些格式都可以有效地减少代码的嵌套层级,提高代码的可读性和可维护性。选择哪种格式取决于具体的项目需求和编程风格。switch语句
函数分解