|
|
|
發新文章 |
|
|
編寫一函數實現數組的遞歸求和 #include?<stdio.h>
#include?"config.h"


int?sum(int?A[],?size_t?n)
  {
????if?(1?==?n)
 ???? {
????????return?1;
????}
????else
 ???? {
????????return?sum(&A[n-1],?n-1)?+?n;
????}
}


int?main(void)
  {
 ????int?A[]?=? {?1,?2,?3,?5,?9,?1};

????printf("%d\n",?sum(A,?ARRAY_LENGTH(A)));

????return?0;
}頭文件config.h的內容如下: #ifndef?CONFIG_H
#define?CONFIG_H


#define?ARRAY_LENGTH(x)?sizeof(x)/sizeof(x[0])


#endif編寫一函數實現str到long的轉換 #include?<stdio.h>
#include?<string.h>
#include?<assert.h>



long?str2long(const?char*?str)
  {
????long?result?=?0;

????while?('\0'?!=?*str)
 ???? {
????????result?=?result?*?10?+?(*str?-?'0');
????????++str;
????}

????return?result;
}




int?main(void)
  {
????char?*str?=?"1234";

????printf("\n%d\n",?str2long(str));

????return?0;
}上面的代碼沒有考慮負數^_^ 實現strcpy函數 char?*mystrcpy(char?*dst,?const?char?*src)
  {
????assert(NULL?!=?dst?&&?NULL?!=?src);
????while?(*dst++?=?*src++);
????
????return?dst;
}?


int?main(void)
  {
????char?*dst[20];
????char?*src?=?"test";
????mystrcpy(dst,?src);

????puts(dst);

????return?0;
}判斷一個整數是否是回文 long?symm(long?n)
  {
????long?i,?m;
????m?=?0;
????i?=?n;
????while?(i)
 ???? {
????????m?=?m?*?10?+?i?%?10;
????????i?/=?10;
????}
????return?(n?==?m???1:0);
}實現Insertion sort #include?<stdio.h>
#include?<string.h>

typedef?int?ElemType;

void?InsertionSort(ElemType?A[],?size_t?n)
  {
????int?i;
????int?pass;
????ElemType?tmp;

????for?(pass?=?1;?pass?<?n;?pass++)
 ???? {
????????tmp?=?A[pass];
????????for?(?i?=?pass;?i?>?0?&&?A[i-1]?>?tmp;?i--)
 ???????? {
????????????A[i]?=?A[i-1];
????????}
????????A[i]?=?tmp;
????}
}

int?main(void)
  {
????int?i;
 ????ElemType?A[]?=? {1,?2,?4,?8,?6,?98,?11,?25,?44,?35};

????puts("Before?sort:");
????for(i?=?0;?i<?sizeof(A)/sizeof(ElemType);?i++)
 ???? {
????????printf("%d??",?A[i]);
????}
????printf("\n");

????InsertionSort(A,?sizeof(A)/sizeof(ElemType));

????puts("After?sort:");
????for(i?=?0;?i<?sizeof(A)/sizeof(ElemType);?i++)
 ???? {
????????printf("%d??",?A[i]);
????}

????printf("\n");

????return?0;
}
|