[英]Binary to decimal
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#中做到這一點。
不, pow()
不是關鍵字,它是標准庫math.h
的函數。
在這種情況下,對於C ++和C#,您可以輕松地通過移位將其替換:
(int) pow(2, count) == 1 << count
以上對於count
所有正值都是正確的,直到平台/語言的精度極限。
我認為使用移位可以更輕松地解決整個問題。
檢查一下:
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;
}
您必須照顧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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.