2009年5月26日 星期二

函式指標 計算應用 (C)

//===============================================================
// 20090523/24/26 知識 +
// http://knowledge.yahoo.com.tw/question/question?qid=1609052303386
// http://knowledge.yahoo.com.tw/question/question?qid=1609052411327
// http://knowledge.yahoo.com.tw/question/question?qid=1609052606389
// 發問者 :( ) http://tw.knowledge.yahoo.com/my/my?show=AB04901004
//===============================================================


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef double T (double *Op1, double *Op2);
T add, sub, mul, div, fac, por;
T *pM[] = { add, sub, mul, div, fac, por };
char* msg[] = { "相加", "相減", "相乘", "相除", "階乘", "次方" };

//=========== 主程式 ...
int main(void)
{
double ans, Op1, Op2;
int i, num, opN = sizeof(pM)/sizeof(*pM);
while(1)
{
printf("\n要做哪種運算? ");
for(i=0; i<opN; i++) printf("%d)%s ", i, msg[i]);
printf(",其它)離開 \n");
if (scanf("%d",&num)!=1 || num<0 || num >= opN) break;
ans = pM[num](&Op1, &Op2);
printf("%s的結果 = %.2lf \n", msg[num], ans);
}
system("pause");
return 0;
}

//---------
double Input(int no, int mode=-1)
{
double d;
while(!fflush(stdin)) //淨空輸入
{
printf("請輸入第%d個數值 : ", no );
if (scanf("%lf", &d)!=1) printf("輸入錯誤!! 重新");
else if (mode==0 && d==0) printf("數值不得為0!! 重新");
else break;
}
return d;
}

int InputInt()
{
int n;
while (!fflush(stdin)) //淨空輸入
{
printf( "請輸入一個整數 : " );
if (scanf("%d", &n)==1) break;
printf("輸入錯誤!! 重新");
}
return n;
}
//---------
double add(double *Op1, double *Op2)
{
*Op1 = Input(1); *Op2 = Input(2);
return (*Op1) + (*Op2);
}

double sub(double *Op1, double *Op2)
{
*Op1 = Input(1); *Op2 = Input(2);
return (*Op1) - (*Op2);
}

double mul(double *Op1, double *Op2)
{
*Op1 = Input(1); *Op2 = Input(2);
return (*Op1) * (*Op2);
}

double div( double *Op1, double *Op2)
{
*Op1 = Input(1); *Op2 = Input(2, 0);
return (*Op1) / (*Op2);
}

double fac(double *Op1, double *Op2)
{
double ans = 1; *Op2 = 0;
int num = InputInt();
for( *Op1 = num; num>=2; num--) ans *= num;
return ans;
}

double por(double *Op1, double *Op2)
{
*Op1 = Input(1); *Op2 = Input(2);
return pow(*Op1, *Op2);
}
//---------------------------------

沒有留言:

張貼留言