C语言 要求输入两个浮点数 如何判断这两个数字是不是数字

如题!

下面是实现的一种方法,C Prime Plus第232页
float code;
int status;
printf("Enter a number : \n");
while ((status = scanf("%f", &code)) !=1)
{
if (status != 1)
scanf("%*s");
printf("Enter a number : \n");
}

PS:scanf("%*s");表示从缓冲区读一个字符串,不保存到变量里
关键是理解字符是先存在缓冲区,接收到endl/flush以后才发送到内存空间。在这个过程中,可以应用流(iostream)的函数直接对输入输出作判断--cin.expections(iso_::failbit)。

推荐读物:C Prime Plus
高质量C、CPP编程指南
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-02-08
将输入的字符串解析吧,比如输入:
1.2345 129.99112
这是一个字符串,先将字符串按空格分解为两个子串,然后将得到的两个子串中的每个字符做判断:是否是数字或者点号,每个子串中是否有一个点号。
第2个回答  2010-02-08
只写了输入一个的,两个的同理,自己写吧
#include <stdio.h>
#include <math.h>
int is_numeric(char *);
int main()
{
float a1;
float a[2]={0.0};
char rec1[20]={'\0'};
char *p1;
int flag=0,count1=1,count2=1;
printf("please input float number:\n");
scanf("%s",rec1);
p1=rec1;
while(!is_numeric(p1))
{
printf("error!please input correct number!\n");
scanf("%s",rec1);
}
while (*p1!='\0')
{
if (*p1=='.')
{
flag=1;
p1++;
continue;
}
if (!flag)
{
a[0]=a[0]*10+(*p1-48);
}

if (flag)
{
a[1]=a[1]+(*p1-48)*pow(0.1,count1);
count1++;
}
p1++;
}
a1=a[0]+a[1];
printf("the number you input is:\n%f\n",a1);

return 0;
}
int is_numeric(char *p)
{
if (*p>=48 && *p<=57)
{
return 1;
}
else
return 0;

}
相似回答