有什么办法检查一个表示float的字符串表示
1个回答
展开全部
简单判断 字符串表示 的 float 数值 是否对 用 sscanf(); 若返回0,则是错的。若返回1,则可能是对的,也可能不完全对。
程序例子:
#include <stdio.h>
int main()
{
char s1[]="123.456",s2[]="-123.45E-02",s3[]="xyz";
float a1,a2,a3;
if ( sscanf(s1,"%f",&a1)==1) printf("s1=%s, a1=%g\n",s1,a1);
else printf("s1 is a wrong string!\n");
if ( sscanf(s2,"%f",&a2)==1) printf("s2=%s, a2=%g\n",s2,a2);
else printf("s2 is a wrong string!\n");
if ( sscanf(s3,"%f",&a3)==1) printf("s3=%s, a3=%g\n",s3,a3);
else printf("s3 is a wrong string!\n");
return 0;
}
输出:
s1=123.456, a1=123.456
s2=-123.45E-02, a2=-1.2345
s3 is a wrong string!
程序例子:
#include <stdio.h>
int main()
{
char s1[]="123.456",s2[]="-123.45E-02",s3[]="xyz";
float a1,a2,a3;
if ( sscanf(s1,"%f",&a1)==1) printf("s1=%s, a1=%g\n",s1,a1);
else printf("s1 is a wrong string!\n");
if ( sscanf(s2,"%f",&a2)==1) printf("s2=%s, a2=%g\n",s2,a2);
else printf("s2 is a wrong string!\n");
if ( sscanf(s3,"%f",&a3)==1) printf("s3=%s, a3=%g\n",s3,a3);
else printf("s3 is a wrong string!\n");
return 0;
}
输出:
s1=123.456, a1=123.456
s2=-123.45E-02, a2=-1.2345
s3 is a wrong string!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询