如何检查用户输入的是在C浮点数? [英] How to check if user input is a float number in C?

查看:97
本文介绍了如何检查用户输入的是在C浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序如果数字用户输入是float哪些检查,但它不工作。我试图检查与 scanf函数,但是这也不能工作。

 的#include<&stdio.h中GT;诠释主要(无效){        浮NUM1;        的printf(请输入数字:);
        scanf函数(%LF,&安培; NUM1);        如果(scanf函数(%LF)){                的printf(好\\ n);
        }
        其他{
                的printf(坏\\ n);
        }
}


解决方案

让你的 scanf函数(3)

您需要检查这样的返回值

 双重价值;
如果(scanf函数(%LF,&安培;价值)== 1)
    的printf(这是浮动:%F \\ N,值);
其他
    的printf(这不是漂浮... \\ n);

有一种方法我preFER,因为它给后续投入更多的控制, scanf()的很少真正有用的。相反,尝试与fgets()

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&文件ctype.h GT;
INT主要(无效)
{
    炭缓冲器[100];
    双重价值;
    字符* endptr;
    如果(与fgets(缓冲区,缓冲区尺寸标准输入)== NULL)
        返回-1; /* 意外的错误 */
    值=的strtod(缓冲,&安培; endptr);
    如果((* endptr =='\\ 0')||(isspace为(* endptr)!= 0))
        的printf(这是浮动:%F \\ N,值);
    其他
        的printf(这不是漂浮... \\ n);
}

I am trying to create a program which checks if the number user enters is a float, but it does not work. I tried to check with scanf, but that did not work either.

#include <stdio.h>

int main(void) {

        float num1;

        printf("enter number: ");
        scanf("%lf", &num1);



        if (scanf("%lf")) {

                printf("Good \n");
        }
        else {
                printf("Bad \n");
        }
}

解决方案

Have you read any documentation on scanf(3)?

You need to check the return value like this

double value;
if (scanf("%lf", &value) == 1)
    printf("It's float: %f\n", value);
else
    printf("It's NOT float ... \n");

There is a way I prefer because it gives more control on subsequent input, scanf() is rarely really useful. Instead try fgets()

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
    char buffer[100];
    double value;
    char *endptr;
    if (fgets(buffer, sizeof(buffer) stdin) == NULL)
        return -1; /* Unexpected error */
    value = strtod(buffer, &endptr);
    if ((*endptr == '\0') || (isspace(*endptr) != 0))
        printf("It's float: %f\n", value);
    else
        printf("It's NOT float ...\n");
} 

这篇关于如何检查用户输入的是在C浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆