2013-03-28 200 views
-2

該代碼應該將二進制數轉換爲十進制數,但它不。任何人都可以請檢查我可能出錯的地方。從二進制轉換爲十進制

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

int main() 
{ 

    char s[40]; 
    int base; 
    int index,n,p,sum=0;  /* n is the number of digits in the converted value */ 

    printf("enter the number and base: "); 
    scanf("%s %d",s,&base); 

    for(n=strlen(s)-1;n>=0;n--) 
    { 
     p=strlen(s); 
     for(index=strlen(s)-(p-1); index<=p; index++) 
     { 
     sum += s[index] * pow(base,n); 
     } 
    } 
    printf("decimal no. is %d",sum); 
    printf("\n"); 

} 

輸出::

enter the number and base:1011 
2 

十進制沒有。是1487

+3

你似乎很喜歡的strlen()了很多。 – wildplasser 2013-03-28 00:32:55

+0

你也喜歡循環。你可以用一個循環做到這一點,你甚至不需要math.h.建議:嘗試用自然語言向自己描述如何去做這件事。一步一步仔細思考,然後將其轉爲代碼。 – 2013-03-28 00:33:39

+0

'p = strlen(s);'是不變的,你永遠不會改變's' – corny 2013-03-28 00:35:37

回答

1
p = 1; sum = 0; 
for(n=strlen(s)-1;n>=0;n--) 
{ 
    sum += (s[n] - '0') * p; 
    p = p << 1; 
} 

而不是你的雙循環我推薦上面的代碼。

+0

如果我明白爲什麼有人認爲這個答案無益,我將不勝感激。謝謝。 – 2013-03-28 00:37:49

+0

看起來好像你對倒票不高興。這不是我,但我建議*測試*你的代碼... – Sebivor 2013-03-28 01:23:20

+0

我不沮喪,我只是想從我在Stackoverflow的經驗中學習。如果他們不告訴我我的答案中沒有什麼幫助,那我該如何改進呢?並感謝您的建議,但我幾乎沒有時間鍵入我的答案。另外,我不相信這個會有任何錯誤。 – 2013-03-28 01:35:10

2

有幾個問題與您的代碼:

  • 你只需要一個,不是兩個,循環
  • 您正在使用代表數字的字符,即'0''1',數字的不是值
  • 你的數學有點不合適:在pow(base,n)n應該用從後面開始的數字位置代替。

這裏是你如何修復你的代碼:

// Power starts at the length-1 
p=strlen(s)-1; 
for(index=0; index < strlen(s); index++, p-- /* <<< Power counts down */) 
{ 
    sum += (s[index]-'0') * pow(base,p); 
    //    ^^^-- Note the minus '0' above: 
    //      That's what gives you a digit's value 
} 

這裏是一個demo on ideone

+0

如果沒有算術例外(例如,整數溢出),通過「二進制」的定義證明第n個二進制數將乘以2,n-1次將其置位值:for(index = 0 ; s [index]; index ++){sum * = 2; sum + = s [index] - '0'; }'。由於pow使用浮點數並需要長度,因此它不如一個簡單的乘法那麼可接受。 – Sebivor 2013-03-28 01:32:42

+0

@modifiablelvalue很顯然,這與你典型的「模型解決方案」相去甚遠:如果我在生產中解決這個問題,我不僅會跳過'pow',而且會跳過'strlen',並且將整個事件放在一行中。然而,我想要與OP的代碼最相似的解決方案,所以我保持了「pow」的地位。 – dasblinkenlight 2013-03-28 01:41:13

+0

不夠公平......如果OP繼續閱讀並理解這兩條評論,那麼一切都會更好!你有我的投票。 – Sebivor 2013-03-28 01:44:31

0

我的回答是:

#include <stdio.h> 
#include <math.h> 
#include <string.h> 
int main(int argc, char *argv[]){ 
    char s[40]; 
    int base; 
    int index,n,p,sum=0;/*n is the number of digits in the converted value */ 
    printf("enter the number and base: "); 
    scanf("%s %d",s,&base); 

    p = strlen(s); 
    index = 0; 
    for(n = 40 - p - 1; n >= 0; n--) 
     sum += (s[n] - '0') * pow(base, index++); 
    printf("decimal no. is %d",sum); 
    printf("\n"); 
    return 0; 
} 
+1

你的答案是表達未定義行爲的算法? – Sebivor 2013-03-28 01:45:53