#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isvalidReal(char str[100]);
int main(int argc, char *argv[]) {
//input
char str[100];
printf("please input a double-precision number:\n");
gets(str);
//call the fuction
int ret=isvalidReal(str);
//judge&output
if(ret==1){
printf("Your number is a real number\n");
}
if(ret==0){
printf("Your number is not a real number\n");
}
system("pause");
return 0;
}
int isvalidReal(char str[100]){
int i,j,count;
int sign=0;
char str2[100],str3[100];
//first situation
if(str[0]=='+'||str[0]=='-'){
//找到小数点的位置
for(i=1;i<strlen(str);i++){
if(str[i]=='.'){
count=i+1;
break;
}
}
//排除+aa.03
for(j=0;j<i-1;j++){
str3[j]=str[j+1];
}
if (strspn(str3, "0123456789")!=strlen(str3)){
sign=0;
}
else{
for(j=0;j<strlen(str)-i;j++){
str2[j]=str[j+count];
}
//排除+0.0a
if (strspn(str2, "0123456789")==strlen(str2)){
sign=1;
}
}
}
//second situation
else if(str[0]=='.'){
for(j=0;j<strlen(str);j++){
str2[j]=str[j+1];
}
if (strspn(str2, "0123456789")==strlen(str2)){
sign=1;
}
}
//third situation
else{
for(i=1;i<strlen(str);i++){
if(str[i]=='.'){
count=i+1;
break;
}
}
//排除aa.03
for(j=0;j<i;j++){
str3[j]=str[j];
}
if (strspn(str3, "0123456789")!=strlen(str3)){
sign=0;
}
else{
//排除99.aa
for(j=0;j<strlen(str)-i;j++){
str2[j]=str[j+count];
}
if (strspn(str2, "0123456789")==strlen(str2)){
sign=1;
}
}
}
return sign;
}
C语言判断输入有效小数
最新推荐文章于 2023-05-22 11:07:10 发布