C 只输入小数

发布于 2024-12-13 21:17:05 字数 683 浏览 4 评论 0原文

我试图在简单的 C 应用程序中将输入限制为仅数字,但是我收到警告。我怀疑这与以下部分有关。版本一是正确的做事方式吗?谢谢。

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<"0" || string[i]>"9")
        valid= FALSE;
}

或者

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<'0' || string[i]>'9')
        valid= FALSE;
}

我的其余代码是

    void main()

{
    char number[4];
    printf("Please enter a decimal number: ");
    gets(number);   
    if (numeric(number))
        printf("'%s' is a valid number\n", number);
    else
        printf("'%s' is an invalid number\n", number);
}

为了澄清我必须按照我正在做的练习给出的方式进行检查。谢谢。

I'm trying to restrict the input to only numerics in a simple C application however I get a warning. I suspect it's to do with the following segment. Is version one the proper way of doing things? Thanks.

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<"0" || string[i]>"9")
        valid= FALSE;
}

OR

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<'0' || string[i]>'9')
        valid= FALSE;
}

rest of my code is

    void main()

{
    char number[4];
    printf("Please enter a decimal number: ");
    gets(number);   
    if (numeric(number))
        printf("'%s' is a valid number\n", number);
    else
        printf("'%s' is an invalid number\n", number);
}

To clarify I have to do the check in the fashion given according to the exercise I'm doing. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七堇年 2024-12-20 21:17:05

第一版是完全错误的。它进行指针比较,因为字符串文字会衰减为指针,并且字符会提升为 int

第二个版本很接近,但您确实应该使用 中的 isdigit

顺便说一句,你知道 i i i i i i i i i i 循环终止条件中的 strlen(string) 将线性时间算法变为二次时间算法?

Version one is entirely wrong. It does pointer comparisons, because string literals decay to pointers and characters are promoted to int.

Version two is close, though you should really use isdigit from <ctype.h>.

Btw., are you aware that i < strlen(string) in a loop termination condition turns linear-time algorithms into quadratic-time ones?

束缚m 2024-12-20 21:17:05

你不能只使用 if (scanf ("%d", &n)==1) 或调用 strtol 吗?

Can't you just use if (scanf ("%d", &n)==1) or call strtol ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文