一,將十進制資料轉換為二進制:
//***********************************************Console.WriteLine("將十進制轉換為二進制!");
Console.WriteLine("請輸入一個數字!");
string a = Console.ReadLine();
string result = "";
if (!string.IsNullOrWhiteSpace(a))
{
try
{
int b = int.Parse(a);
while (b >= 0)
{
if (b != 1 && b != 0)
{
int c = b / 2;
int x = b % 2;
result = x + result;
b = c;
}
else
{
result = b + result;
break;
} }
Console.WriteLine("轉換結果為" + result);
Console.ReadKey();
}
catch
{
Console.WriteLine("err:格式轉換錯誤!");
Console.ReadKey();
} }
else
{
Console.WriteLine("err:未輸入任何字符!");
Console.ReadKey();
}
//******************************************************** 二,將二進制資料轉化為十進制: //********************************************************
Console.WriteLine("請輸入一個數");
string x = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(x))
{
double result = 0;
int j = 0;
int a = x.Length;
try {
for (int i = a - 1; i >= 0; i--)
{
int b = int.Parse(x.Substring(i, 1));
if (j < a)
{
double aa = Math.Pow(2, j);
result = result + b * aa;
j++;
}
}
Console.WriteLine("轉換為十進制后為" + result);
Console.ReadKey();
}
catch {
Console.WriteLine("err:格式轉換錯誤!");
Console.ReadKey();
}
}
else {
Console.WriteLine("err:未輸入任何字符!");
Console.ReadKey();
} //******************************************************** 以上就是二進制和十進制資料之間的轉換代碼,代碼是基于控制臺應用程式中寫出來的,中間有用到的Math.Pow()方法,
Math.pow() 函式回傳基數(base)的指數(exponent)次冪,即 baseexponent,
語法:
Math.Pow(base, exponent)
引數:
base基數 exponent指數
描述
由于 pow 是 Math 的靜態方法,所以應該像這樣使用:Math.pow(),而不是作為你創建的 Math 物件的方法,
示例
使用 Math.pow
1 function raisePower(x,y) { 2 return Math.pow(x,y) 3 }View Code
如果 x 是 2 ,且 y 是 7,則 raisePower 函式回傳 128 (2 的 7 次冪),
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/36081.html
標籤:C#
