
using System;
using System.Collections.Generic;
/*
本实例实现二进制验证、然后转换成十进制数。
技术要点:continue和break使用
Math.Pow(double x,double y)方法使用(求x的y次方)
*/
public class MyClass
{
public static void Main(string[] args)
{
goon:
TwoToTen();
goto goon;
}
#region TwoToTen()方法
public static void TwoToTen()
{
int y=0;int z=0;int starter=0;
Console.Write("\n-----二进制转换成十进制算法演示-----\n");
Reinput:
Console.Write("\n请输入二进制数:");
string x=Convert.ToString(Console.ReadLine());
bool isBinary=false;
for(int i=0;i<x.Length;i++)
{
string cc=x.Substring(i,1);
if(cc=="0" || cc=="1")
{
isBinary=true;
}
else
{
isBinary=false;
break;//当有不是0或1的数字时,直接退出
}
}
if(isBinary==false)
{
Console.WriteLine("\n您输入的数据不是二进制!(二进制由0、1组成)\n");
//输入有误时,跳转到重新语句
goto Reinput;
}
z=x.Length;
//当转换的数为0或1时,作特殊处理。
if(z==1)
{
Console.Write("\n转成十进制数为:"+x+"\n");
}
else
//当转换的数长度为>1时
{
for(starter=0;starter<=z-1;starter++)
{
int xs=Convert.ToInt32(x.Substring(starter,1));
//如果二进制数为0,则直接进入下一循环
if(xs==0)
{
continue;
}
//转换方式见图1
y=y+(int)(xs*Math.Pow(2,(z-starter-1)));
//Math.Pow(double x,double y)用于求x的y次方
}
Console.Write("\n转成十进制数为:"+y+"\n");
}
}
#endregion
}