1. 程式人生 > >C語言----結構體---結構體與函數

C語言----結構體---結構體與函數

urn 全局變量 月的天數 [] strong ret 例子 c語言 +=

結構作為參數的函數

  1. 整個結構可以作為參數傳入函數
  2. 這時是在函數中新建了一個結構變量,並復制調用這個結構的值(重點,只是把值傳入函數,而函數外面真正的變量並沒有改變,與數組不同)
  3. 函數也可以返回一個結構

直接來個簡單的例子吧:

問題:用戶輸入今天的日期,輸出明天的日期。

提示:閏年,每個月最後一天,

代碼:

#include <stdio.h>
#include <stdbool.h>
/* 根據今天的日期算出明天的日期。*/

//結構體放在函數外側,相當於一個全局變量,所有的函數都能使用。
struct date
{
  int month;
  int day;
  int year;
};    //記住這個分號

bool is_leap(struct date d);  //判斷是否為閏年
int numbersofdays(struct date d);  //給出這個月的天數

int main(int argc, char const *argv[])
{
  struct date today;   //定義兩個結構體變量
  struct date tomorrow;
  int days;
  int flag=1;  //實現輸入控制

  printf("請輸入今天的日期(9-24-2012):");
  scanf("%i-%i-%i",&today.month,&today.day,&today.year);

  days = numbersofdays(today);
  tomorrow = today;  //可以像一般變量一樣賦值
  if(today.day<days && today.month <=12){
    tomorrow.day = today.day + 1;
  }else if(today.day == days && today.month <12){
    tomorrow.day = 1;
    tomorrow.month +=1;
  }else if(today.day == days && today.month == 12){
    tomorrow.day =1;
    tomorrow.month =1;
    tomorrow.year+=1;
  }else{
    flag = 0;
    printf("輸入有誤!");
  }

  if(flag){
    printf("明天的日期是:");
    printf("%i-%i-%i\n",tomorrow.month,tomorrow.day,tomorrow.year);
  }

  return 0;
}

bool is_leap(struct date d)
{
  bool is = false;
  if((d.year%4==0 && d.year%100!=0) || d.year%400==0)
    is = true;
  return is;
}


int numbersofdays(struct date d)
{
  int days;
  int dayspermonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
  if(d.month==2 && is_leap(d))
  {
    days = 29;
  }
  else

  {
    days = dayspermonth[d.month-1];
  }

  return days;
}

C語言----結構體---結構體與函數