C 函數示例

2018-05-19 19:39 更新

學習C - C函數示例

C中的聲明函數可以寫成如下

  void foo(){ 
      printf("foo() was called\n"); 
  } 

我們把這個函數放在main()函數上面。 然后,我們可以調用這個函數,forinstance foo()。


  #include <stdio.h> 
//w  w w. jav a  2 s  . com
  void foo(){ 
      printf("foo() was called\n"); 
  } 

  int main(int argc, const char* argv[]) { 

    foo(); 
    return 0; 
  } 

上面的代碼生成以下結果。



例子

我們還可以在main()函數的下面聲明一個函數,但是我們必須聲明我們的函數名。


  #include <stdio.h> 
/*from   www. ja v  a2  s . c om*/
  // implicit declaration for functions 
  void boo(); 

  int main(int argc, const char* argv[]) { 

    boo(); 
    return 0; 
  } 

  void boo(){ 
      printf("boo() was called\n"); 
  } 

上面的代碼生成以下結果。



帶參數和返回值的函數

您可能需要創(chuàng)建一個具有參數和返回值的函數。

這很容易因為你只是調用return進入你的函數。


  #include <stdio.h> 
/*from   w  w  w . j a v  a2s  .c o  m*/
  // implicit declaration for functions 
  int add(int a, int b); 

  int main(int argc, const char* argv[]) { 

    int result = add(10,5); 
    printf("result: %d\n",result); 

    return 0; 
  } 

  int add(int a, int b){ 
      return a + b; 
  } 

上面的代碼生成以下結果。

數組參數的函數

我們也可以聲明一個函數帶有數組作為參數。

要知道數組大小,你的函數應聲明數組大小。

將此代碼寫入程序以進行說明。


  #include <stdio.h> 
/*  ww w.j  ava 2s  .com*/
  // implicit declaration for functions 
  double mean(int numbers[],int size); 

  int main(int argc, const char* argv[]) { 

    int numbers[8] = {8,4,5,1,4,6,9,6}; 
    double ret_mean = mean(numbers,8); 
    printf("mean: % .2f\n",ret_mean); 

    return 0; 
  } 

  double mean(int numbers[],int size){ 
      int i, total = 0; 
      double temp; 

      for (i = 0; i < size; ++i){ 
          total += numbers[i]; 
      } 

      temp = (double)total / (double)size; 
      return temp; 
  } 

上面的代碼生成以下結果。

函數參數指針

我們可以將指針作為參數傳遞給我們的函數。

為了說明,我們可以創(chuàng)建swap()交換我們的價值觀。


  #include <stdio.h> 
/*w  w  w . ja va  2 s .c om*/
  // implicit declaration for functions 
  void swap(int *px, int *py); 

  int main(int argc, const char* argv[]) { 

    int *x, *y; 
    int a, b; 

    a = 10; 
    b = 5; 

    // set value 
    x = &a; 
    y = &b; 

    printf("value pointer x: %d \n",*x); 
    printf("value pointer y : %d \n",*y); 

    swap(x,y); 
    printf("swap()\n"); 
    printf("value pointer x: %d \n",*x); 
    printf("value pointer y : %d \n",*y); 
    return 0; 
  } 

  void swap(int *px, int *py){ 
      int temp; 

      // store pointer px value to temp 
      temp = *px; 
      // set pointer px by py value 
      *px = *py; 
      // set pointer py by temp value 
      *py = temp; 
  } 

上面的代碼生成以下結果。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號