首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用C语言发出一个程序,以检查一个数字是否可以被100整除

用C语言发出一个程序,以检查一个数字是否可以被100整除
EN

Stack Overflow用户
提问于 2016-11-25 18:17:13
回答 2查看 2.4K关注 0票数 1

我用C语言编写了一个程序来检查输入的数字是否可以被100整除,但是我遇到了一个问题。如果我输入一个11位或更多的数字(当然最后两位数是零),它说这个数字不能被100整除,尽管它是。帮助?

代码语言:javascript
复制
#include <stdio.h>
#include <conio.h>
int main()
{
    long int a;
    printf("Enter the number: ");
    scanf("%d" , &a);
    if(a%100==0)
    {printf("This number is divisible by 100");}
    else
    {printf("This number is not divisible by 100");}
    getch();
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-25 18:21:25

您的号码只是不符合long int类型,所以您得到的实际数字不是您所期望的。尝试使用unsigned long long,但请注意,大于2^64 - 1的数字无论如何都不合适。此外,在这种情况下,您应该使用scanf("%llu", &a)

票数 7
EN

Stack Overflow用户

发布于 2016-11-25 20:24:04

不应该使用scanf的原因之一是数字溢出会引发未定义的行为。您的C库似乎会在溢出时生成一个垃圾值。

如果使用getlinestrtol编写程序,则可以安全地检查溢出并打印正确的错误消息:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int
main(void)
{
    char *linebuf    = 0;
    size_t linebufsz = 0;
    ssize_t len;
    char *endp;
    long int val;

    for (;;) {
        fputs("Enter a number (blank line to quit): ", stdout);
        len = getline(&linebuf, &linebufsz, stdin);
        if (len < 0) {
            perror("getline");
            return 1;
        }
        if (len < 2)
            return 0; /* empty line or EOF */

        /* chomp */
        if (linebuf[len-1]) == '\n')
            linebuf[len--] = '\0';

        /* convert and check for overflow */
        errno = 0;
        val = strtol(linebuf, &endp, 10);
        if ((ssize_t)(endp - linebuf) != len) {
            fprintf(stderr, "Syntactically invalid number: %s\n", linebuf);
            continue;
        }
        if (errno) {
            fprintf(stderr, "%s: %s\n", strerror(errno), linebuf);
            continue;
        }

        if (val % 100 == 0)
            printf("%ld is divisible by 100\n", val);
        else
            printf("%ld is not divisible by 100\n", val);
    }
}

我在一台long 64位宽的机器上测试了这一点,所以它可以完成大多数(但不是所有19位数字)的操作:

代码语言:javascript
复制
Enter a number (blank line to quit): 1234567890123456789
1234567890123456789 is not divisible by 100
Enter a number (blank line to quit): 12345678901234567890
Numerical result out of range: 12345678901234567890

Enter a number (blank line to quit): 9223372036854775807
9223372036854775807 is not divisible by 100
Enter a number (blank line to quit): 9223372036854775808
Numerical result out of range: 9223372036854775808

我怀疑在您的计算机上,long只有32位宽,所以您的限制将是2147483647。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40810557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档