2016-11-25 271 views
1

我在C中编写了一个程序来检查输入的数字是否可以被100整除,但是我遇到了问题。如果我输入一个11位数或更多的数字(当然最后两位数字为零),它表示该数字不能被100整除,即使它是。帮帮我?使用C程序检查数字是否可以被100整除

#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(); 
} 
+2

对'long'使用''%ld''。 (或使用'%lld'和'long long') – BLUEPIXY

+0

我试过了,但没有奏效。 – 1234567

+1

添加这个:'printf(“%d \ n”,a);'在你的'scanf'行之后并且尝试10,100,1000,10000等等。你会看到会发生什么,当你阅读在整数溢出,也是为什么。 –

回答

7

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

+0

谢谢!是的,这是整数类型的问题。 – 1234567

+0

@ 1234567 - 很高兴工作 –

0

为什么scanf永远不要使用的原因之一是数字溢出会引发未定义的行为。你的C库似乎在溢出时产生垃圾值。

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

#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位号码:

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

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为您服务。

相关问题