2016-10-02 12 views
0

//輸入「bin」的值後,我沒有得到任何輸出。請幫我解決這個問題。我添加了「bin = bin/10;」但問題仍未解決。我已經編寫了用於從二進制轉換爲十進制的代碼,但沒有得到輸出。沒有什麼是在屏幕上打印

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

int main() 
{ 
    int ar[20],bin,i=0,sum=0,j,c; 
    printf("Enter a Binary number\n"); 
    scanf("%d",&bin); 
    while(bin!=0||bin!=1) 
    { 
     c=bin%10; 
     ar[i]=c; 
     i++; 
    } 
    ar[i]=c; 

    for(j=0;j<=i;j++) 
    { 
     sum=sum+(ar[j]*pow(2,j)); 
    } 
    printf("%d",sum); 
    return 0; 
} 

更新:while循環,現在看起來是這樣的:

while(bin!=0||bin!=1) 
    { 
     c=bin%10; 
     ar[i]=c; 
     bin=bin/10; 
     i++; 
    } 
+0

所有'ar'元素都將得到與'bin'相同的值,從不改變。 – alk

+0

您的標題提示像'1001'和輸出:'9'這樣的輸入。那是你要的嗎?在這種情況下,你的程序遠不是那樣。 – 4386427

+0

我已經更新了代碼,請再次檢查。 –

回答

2

此行

while(bin!=0||bin!=1) 

將導致一個無限循環的

bin!=0 || bin!=1 

將始終評估true截止到t Ó使用||

在詞:bin將總是從0 不同或者不同於1.

實施例:

如果bin是2兩部分將是true

如果bin爲1,則第一部分將爲true,並且由於或(),您獲得)

如果bin爲0的第一部分將是false但第二個將是true,你會得到true因或(||

也許你想要的和,即&&,而不是||

此外,您必須在循環內更改bin的值。如果你不這樣做,那也將導致無限循環。

從你的標題看來你想要的東西完全不同於你當前的代碼。可能是這樣的:

#include<stdio.h> 
#include<stdlib.h> 

int main() 
{ 
    char input[100]; 
    int value = 0; 

    printf("Input a binary: "); 
    if (fgets(input, 100, stdin) == NULL) // Read a whole line of input 
    { 
    printf("error\n"); 
    return 0; 
    } 

    char* t = input; 
    while (*t == '0' || *t == '1') // Repeat as long as input char is 0 or 1 
    { 
    value = value*2;    // Multiply result by 2 as this is binary conversion 
    value = value + *t - '0';  // Add value of current char, i.e. 0 or 1 
    ++t;       // Move to the next char 
    } 

    printf("Decimal value: %d\n", value); 

    return 0; 
} 
+0

&&也不起作用 –

+1

@RohitVishwakarma - 然後有一個以上的錯誤;-) – 4386427

+0

你能否將我的代碼複製到你的電腦上並嘗試運行。 –

0

您的代碼運行到無限循環。

while(bin!=0||bin!=1) 
{ 
    c=bin%10; 
    ar[i]=c; 
    i++; 
} 

您必須更新你的bin的值作爲

bin = bin/10; 

我已經編輯你的代碼。在這裏,看看

#include<stdio.h> 
#include<math.h> 
int main() 
{ 
int ar[20],bin,i=0,sum=0,j,c; 
printf("Enter a Binary number\n"); 
scanf("%d",&bin); 
while(bin!=0) 
{ 
    c=bin%10; 
    ar[i]=c; 
    i++; 
    bin = bin/10; 
} 
//ar[i]=c; 

for(j=0;j<i;j++) 
{ 

    sum=sum+(ar[j]*pow(2,j)); 
} 
printf("%d",sum); 
return 0; 

} 
+0

你能否改正它並在PC上運行它。 –

+0

@RohitVishwakarma你的條件是錯誤的。嘗試刪除bin!= 1 這隻會解決您的循環錯誤。你的邏輯錯了。我建議你最好看看你的邏輯。 –

+0

謝謝,它的工作 –

1

[過長評論]

確定,再次:

while循環應該循環只要(bin!=0||bin!=1)是真實的。

這意味着它應該打破相反:

!(bin!=0||bin!=1) 

應用De Morgan's Law我們發現上面的等價於:

(bin==0 && bin==1) 

綜觀上述密切,我們看到這是真實的是要求bin同時等於0和1。這不可能。所以循環將永遠不會結束。

+0

以前我錯過了一個聲明「bin = bin/10;」但現在我添加了。請再次檢查。 –

相關問題