#define ERR 5
#define OK 6
#include <stdio.h>
int status;
double result,sig,scale;
int sign(int c)/*處理數(shù)的符號(hào)函數(shù)*/
{
if(c=='-')/*若為負(fù)號(hào),置負(fù)數(shù)標(biāo)記*/
sig=-sig;
}
int integer(int c)/*轉(zhuǎn)換整數(shù)部分,轉(zhuǎn)換一位整數(shù)位*/
{
result=result*10.0+c-'0';
}
int decimal(int c)/*轉(zhuǎn)換小數(shù)部分,轉(zhuǎn)換一位小數(shù)位*/
{
result+=(c-'0')*scale;
scale/=10.0;
}
/*狀態(tài)表*/
int statbl[ ][4]={{ 1,2,3,ERR},/*0*/
{ERR,2,3,ERR},/*1*/
{OK,2,4,OK},/*2*/
{ERR,4,ERR,ERR},/*3*/
{OK,4,OK,OK}};/*4*/
/*轉(zhuǎn)換函數(shù)表*/
int(*funtbl[ ][4])( )={{sign,integer,NULL,NULL},
{NULL,integer,NULL,NULL},
{NULL,integer,NULL,NULL},
{NULL,decimal,NULL,NULL},
{NULL,decimal,NULL,NULL}};
int readreal(double *dp)
{
int c,ckind;
sig=1.0;
result=0.0;
scale=0.1;
while((c=getchar( ))==' '||c=='\n'||c=='\t');/*跳過(guò)前導(dǎo)空白符*/
status=0;/*置初始狀態(tài)*/
for(;;)
{
/*分類當(dāng)前字符*/
if(c=='+'||c=='-') ckind=0;/*數(shù)的符號(hào)字符*/
else if(c>='0'&&c<='9') ckind=1;/*數(shù)字符*/
else if(c=='.') ckind=2;/*小數(shù)點(diǎn)*/
else ckind=3;/* 其它字符 */
if(funtbl[status][ckind])/* 如有轉(zhuǎn)換函數(shù) */
(*funtbl[status][ckind])(c);/* 執(zhí)行相應(yīng)的函數(shù) */
status=statbl[status][ckind];/*設(shè)置新的狀態(tài)*/
if(status==ERR||status==OK)break;/* 結(jié)束:出錯(cuò)或成功 */
c=getchar();
}
ungetc(c,stdin); /* 歸還數(shù)德結(jié)束符 */
if(status==OK)
{
*dp=result *sig;/* 讀入數(shù)按指針參數(shù)賦給相應(yīng)變量 */
return 1;
}
return -1; /* 出錯(cuò)返回 */
}
main()
{
double x;
clrscr();
printf("\nPlease input real numbers (use nonreal char to end input):\n");
while(readreal(&x)==1)
printf("The real number you input is: %f\n",x);
printf("\nYou have inputted nonreal char.\n Press any key to quit...\n");
getch();
}