2016-11-25 40 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爲您服務。

相關問題