2016-09-19 242 views
-1

數字4,5,6,7和8不斷返回不正確的值,如20,21和31。任何人都可以幫忙嗎?謝謝!我試圖將十進制數轉換爲二進制數,並且正在使用整數1-8。十進制到二進制轉換器(整數1-8)

// This program converts whole numbers from 1 to 8 to their binary equivalent. 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int decimal; 
    int binary; 
    int remainder1; 
    int remainder2; 
    int remainder3; 
    int remainderA; 
    int remainderB; 
    int remainderC; 
// Get the decimal to convert. 
cout << "Enter a whole number between 1 and 8: "; 
cin >> decimal; 

if (decimal==1) 
{ 
     binary = decimal/1; 
     cout << binary; 
    } 
else if (2 <= decimal < 4) 
{ 
     remainder1=decimal%2; 
     remainderA=decimal/2; 
     binary=remainder1/1; 
     cout << remainderA <<binary; 
    } 
else if (4 <= decimal < 8) 
{ 
     remainder2=decimal%4; 
     remainderA=decimal/4; 
     remainder1=remainder2%2; 
     remainderB=remainder2/2; 
     binary=remainder1/1; 
     cout << remainderA <<remainderB <<binary; 
    } 
else if(decimal==8) 
{ 
     remainder3=decimal%8; 
     remainderA=decimal/8; 
     remainder2=remainder3%4; 
     remainderB=remainder3/4; 
     remainder1=remainder2%2; 
     remainderC=remainder2/2; 
     binary=remainder1/1; 
     cout <<remainderA<<remainderB<<remainderC<<binary<<endl; 
    } 
} 
+3

解決這些問題的正確工具是你的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

回答

3

表達式像2 <= decimal < 4,而有效的語法,不要做你認爲他們做的。

改寫爲2 <= decimal && decimal < 4

正式地,2 <= decimal < 4被評估爲(2 <= decimal) < 4,歸因於相關性。這是true < 4false < 4,在兩種情況下均爲true。這解釋了爲什麼你的代碼從4開始分解。

1

您的測試if(4 <= decimal < 8)是不是你的意思, 你需要寫if((4 <= decimal) && (decimal < 8))

什麼if(4<= decimal < 8)方法是:

  • 聲明中介變量(稱之爲value

  • 1 )將4與小數進行比較,如果小數點< = 4,則值= 1 else值 = 0

  • 2)如果(價值< 8)然後...