2017-06-06 102 views
1
#include <stdio.h> 
#include <math.h> 


int main() { 
    long long int bin; 
    int dec=0,i; 

    scanf("%lld", &bin); 
    for(i=0; bin!=0; i++){ 
     if(bin%10==0 || bin%10==1){ 
      dec+=(bin%10)*pow(2,i); 
      bin/=10; 
     } 
     else { 
      printf("Invalid Binary number!!\n"); 
      return 0; 
     } 

    } 
    printf("%d\n", dec); 


    return 0; 
} 

我使這個程序將二進制轉換爲十進制。 網上有很多代碼,但我想知道 這段代碼是否一切正常?這個二進制到十進制的程序是否正確?

+4

當你嘗試它時,它是否給你正確的結果?這不是主要的測試嗎? – AntonH

+0

@AntonH也許有人認爲,如果代碼包含未定義的行爲,它實際上可以給他們鼻惡魔。 –

+0

@EugeneSh。我看到的唯一UB發生在'scanf()'失敗時。 – EOF

回答

0

您的代碼確實有一些問題:

  1. 您應經常檢查scanf失敗。成功時,scanf返回成功填充的參數列表中的項目數,因此如果返回值不是1(對於您的情況),您應該輸出一個錯誤並在那裏停止。
  2. 根本不需要使用pow。 2的冪乘整數與左移相同,但更快,因爲您沒有調用返回double的函數。將*pow(2, i)替換爲<< i,您會得到相同的結果。
  3. 從可用性的角度來看,您應該將消息打印到屏幕上。

這是好多了:

#include <stdio.h> 
#include <math.h> 


int main() 
{ 
    long long int bin; 
    int dec=0,i; 
    printf("Enter a number in base 2: "); 
    if(scanf("%lld", &bin)!=1) 
    { 
     printf("Error reading your input."); 
     return -1; 
    } 
    for(i=0; bin!=0; i++) 
    { 
     if(bin%10==0 || bin%10==1) 
     { 
      dec+=(bin%10) << i; 
      bin/=10; 
     } 
     else 
     { 
      printf("Invalid Binary number!!\n"); 
      return 0; 
     } 

    } 
    printf("That number in base 10 is: %d\n", dec); 


    return 0; 
} 
1

這將是更好的角色來讀取字符,並直接轉換爲一機多號。這更清楚地表達你的意圖。

#include <stdio.h> 
#include <limits.h> 

int main(void) 
{ 
    unsigned long long n = 0; 
    int c; 
    fputs("enter a number in base 2: ", stdout); 
    while ((c = getchar()) != EOF && c != '\n') { 
     if (n >= (ULLONG_MAX >> 1) + 1) { 
      fprintf(stderr, "binary number is too large\n"); 
      return 1; 
     } 
     n <<= 1; 
     if (c == '0') 
      n += 0; 
     else if (c == '1') 
      n += 1; 
     else { 
      fprintf(stderr, "bad binary digit '%c'\n", c); 
      return 1; 
     } 
    } 
    printf("that number in base 10 is %llu\n", n); 
    return 0; 
} 

完全未經測試。作爲練習留下負數(謹慎:移入有符號整數的符號位會引發未定義的行爲)。