顯示具有 C Programming 標籤的文章。 顯示所有文章
顯示具有 C Programming 標籤的文章。 顯示所有文章

2010年6月19日 星期六

function pinter in c (or c++)

/*
funpt.c: a demo of function pointer

to compile:
gcc -o funpt funpt.c -lm

Ching-Han Hsu, Ph.D. (c) 2010
*/

#include
#include
#include

double fun1(double (*fp)(double), double x)
{
printf("in fun1\n");
return fp(x);
}

double sqcos(double x)
{
printf("squared cos\n");
return (cos(x) * cos(x));
}

int main (int argc, char** argv)
{

printf("cos 2.0 = %.3f\n", cos(2.0));
printf("cos 2.0 = %.3f\n", fun1(cos, 2.0));
printf("squared cos 2.0 = %.3f\n", fun1(sqcos, 2.0));

return 0;
}

2010年6月15日 星期二

qsort: a demo to sort float array

#include
#include
#include

int comp(const void *, const void *);

/* for sorting a float array */
int comp(const void *p, const void *q)
{
return ((*(float *)p - *(float *)q) > 0.0 ? 1 : -1);
}

int main(int argc, char *argv[])
{
int i,j;
float *array_1,*array_2;

srand ( time(NULL) );
array_1 = (float*)calloc(sizeof(float),10);

printf("qsort start \n");

for(i=0;i<10;i++)
{
*(array_1 + i ) = (rand()%200)/7.0;
}


for(i=0;i<10;i++)
{
printf("array_1 %d = %f \n",i,*(array_1 + i));
}

printf("-------- \n");

qsort(array_1, 10, sizeof(float), comp);

for(i=0;i<10;i++)
{
printf("array_1 %d = %f \n",i,*(array_1 + i));
}

printf("\n");

return 0;
}

2009年10月7日 星期三

Seed for Rnadom Number Generator

srand ( time(NULL) );
srand48 ( time(NULL) );