2011-04-20 218 views
1
int rem, count = 0; 
long int n=0, b, i; 

count << "Enter the Binary value to convert in Decimal = "; 
cin >> b; 
i = b; 

while (b > 0) 
{ 
    rem = b % 10; 
    n = n + rem * pow(2, count); 
    count++; 
    b = b/10; 
} 

cout << "The decimal value of Binary no. = " << i << " = " << n; 
getch(); 

我在C++中做了這個簡單的程序,現在我想在C#中實現它,但我不能這樣做,因爲我不知道如何實現我在循環中使用的邏輯。 因爲在C++中,關鍵字pow用於乘以2的值,因此我不知道如何在C#中執行此操作。二進制到十進制

+2

我從來沒有使用C#編寫代碼,但Google很快就說過Math.Pow(2,count)是你想要的東西。 – taskinoor 2011-04-20 11:22:42

+0

真的很感謝你的回答@taskinoor,但我不能擺脫我得到的類型鑄造和@javed幫助我這一點。 – avirk 2011-04-20 14:31:03

回答

1

你必須照顧好數據類型的C#

long int n=0, b, i; // long int is not valid type in C#, Use only int type. 

更換pow()Math.Pow()

pow(2, count);    // pow() is a function in C/C++ 
((int)Math.Pow(2, count)) // Math.Pow() is equivalent of pow in C#. 
          // Math.Pow() returns a double value, so cast it to int 
+0

thanx @javed你真的解決我的問題它很容易做到這一點((int)Math.Pow())的幫助。由於@jaapjan向我介紹了這種方法,但沒有提及將它轉換爲double的方式,我繼續收到錯誤,謝謝.......... – avirk 2011-04-20 14:08:52

7

不,pow()不是關鍵字,它是標準庫的功能math.h

您可以輕鬆地更換它在這種情況下,C++和C#,用位移位:

(int) pow(2, count) == 1 << count 

以上是對於count所有正值真實,走上講臺的/語言的極限精確。

我相信整個問題使用移位更容易解決。

2

檢查:

int bintodec(int decimal); 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int decimal; 

    printf("Enter an integer (0's and 1's): "); 
    scanf_s("%d", &decimal); 

    printf("The decimal equivalent is %d.\n", bintodec(decimal)); 

    getchar(); 
    getchar(); 
    return 0; 
} 

int bintodec(int decimal) 
{ 
    int total = 0; 
    int power = 1; 

    while(decimal > 0) 
    { 
     total += decimal % 10 * power; 
     decimal = decimal/10; 
     power = power * 2; 
    } 

    return total; 
} 
0
public int BinaryToDecimal(string data) 
    { 
     int result = 0; 
     char[] numbers = data.ToCharArray(); 

     try 
     { 
      if (!IsNumeric(data)) 
       error = "Invalid Value - This is not a numeric value"; 
      else 
      { 
       for (int counter = numbers.Length; counter > 0; counter--) 
       { 
        if ((numbers[counter - 1].ToString() != "0") && (numbers[counter - 1].ToString() != "1")) 
         error = "Invalid Value - This is not a binary number"; 
        else 
        { 
         int num = int.Parse(numbers[counter - 1].ToString()); 
         int exp = numbers.Length - counter; 
         result += (Convert.ToInt16(Math.Pow(2, exp)) * num); 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      error = ex.Message; 
     } 
     return result; 
    } 

http://zamirsblog.blogspot.com/2011/10/convert-binary-to-decimal-in-c.html