C语言打印月份天数的程序

如何使用Else If 语句和Switch 条件编写C程序来打印月份的天数?众所周知,月份的总天数是:

  • 一月、三月、五月、八月、十月和十二月 = 31 天
  • 四月、六月、九月和十一月 = 30 天
  • 二月 = 28 或 29 天

使用Else If 打印月份天数的C语言程序

此C语言程序将要求用户输入1到12之间的任意数字,其中1代表一月,2代表二月,3代表三月,...,12代表十二月。

根据用户输入的整数值,该程序将打印出该月份的天数。为了实现此目标,我们使用了Else If 语句

/* C Program to Print Number of Days in a Month using Else If Statement */

#include <stdio.h>

int main()
{
  int month;
  printf(" Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  ");
  scanf("%d", &month);
  
  if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 )
  {
  	printf("\n 31 Days in this Month");  	
  }
  else if ( month == 4 || month == 6 || month == 9 || month == 11 )
  {
  	printf("\n 30 Days in this Month");  	
  }  
  else if ( month == 2 )
  {
  	printf("\n Either 28 or 29 Days in this Month");  	
  } 
  else
    printf("\n Please enter Valid Number between 1 to 12");
  
  return 0;
}
C Program to Print Number of Days in a Month using Else If Statement 1

我输入月份数字为5

 Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  5

 31 Days in this Month

我输入月份数字为9

 Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  9

 30 Days in this Month

这次,我们将输入错误的值:15

 Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  15

 Please enter Valid Number between 1 to 12

使用Switch 条件返回月份天数的C语言程序

这是处理多个C编程条件的理想方法。在此程序中,我们使用Switch Case方法来打印月份的天数。

#include <stdio.h>

int main()
{
  int month;
  printf(" Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  ");
  scanf("%d", &month);
  
  switch(month )
  {
  	case 1:
  	case 3:
	case 5: 	
	case 7:
	case 8:
	case 10:
	case 12:			  	
	  	printf("\n 31 Days in this Month");
	  	break;
	
	case 4:	
	case 6:
	case 9:
	case 11:			    	
	  	printf("\n 30 Days in this Month");  
		break;
	
	case 2:
	  	printf("\n Either 28 or 29 Days in this Month");  
	
	default:		  	
	    printf("\n Please enter Valid Number between 1 to 12");
  }
  return 0;
}
 Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  12

 31 Days in this Month

让我尝试输入不同的值

 Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) :  6

 30 Days in this Month