用 C# 將二進位制轉換成十進位制的程式
首先,設定二進位制值 −
int num = 101;
現在,將二進位制分配給一個新變數 −
binVal = num;
在值大於 0 的情況下,迴圈遍歷二進位制數和基數,如下所示:
while (num > 0) {
rem = num % 10;
decVal = decVal + rem * baseVal;
num = num / 10;
baseVal = baseVal * 2;
}示例
以下程式碼是將二進位制轉換為十進位制的程式碼。
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int num, binVal, decVal = 0, baseVal = 1, rem;
num = 101;
binVal = num;
while (num > 0) {
rem = num % 10;
decVal = decVal + rem * baseVal;
num = num / 10 ;
baseVal = baseVal * 2;
}
Console.Write("Binary Number: "+binVal);
Console.Write("
Decimal: "+decVal);
Console.ReadLine();
}
}
}輸出
Binary Number: 101 Decimal: 5
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP