当前位置:编程学习 > C#/ASP.NET >>

二进制转十进制编程C#

这是我写的代码 半忙看看是否有问题 谢谢了

using System;
using System.Collections.Generic;
using System.Text;

namespace jingzhishuzhuanhuan
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个二进制数");
            string number = Console.ReadLine();
            bool flag = false;
            for (int i = 0; i < number.Length; i++)
            {
                string n = number.Substring(i, 1);
                int c = int.Parse(n);
                if (c < 0 || c > 1)
                {
                    flag = true;
                    break;
                }

            }

            if (flag)
            {
                Console.WriteLine("输入的这个数不是二进制数,数字为" + number);
                double x = 0;
                for (int i = 0; i < number.Length; i++)
                {
                    string n = number.Substring(i, 1);
                    double c = double.Parse(n);
                    x = x + c * Math.Pow(2, number.Length - i - 1);
                }
                Console.WriteLine("二进制数" + number + "转换为十进制数为" + x);

            }
            else
            {
                Console.WriteLine("输入的这个数是二进制数,数字为" + number);

            }
        


        }
    }
}

补充: 我自己粗心 

答案:我是这样作这的


using System;
using System.Collections.Generic;
using System .Text ;

namespace windshadowpp1
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   
   string i =Console.ReadLine ();
   try
   {
   Console.WriteLine("二进制{0,3}转成十进制后为{1,3}",i,Convert.ToInt32(i, 2));
   }
   catch(FormatException ex)
   {
    Console.WriteLine (ex.Message);
    
   }
    
   Console.ReadKey ();
   }

}

}
  
 
希望对你的所帮助 。。。。。。。

 

 double x = 0;
                for (int i = 0; i < number.Length; i++)
                {
                    string n = number.Substring(i, 1);
                    double c = double.Parse(n);
                    x = x + c * Math.Pow(2, number.Length - i - 1);
                }
                Console.WriteLine("二进制数" + number + "转换为十进制数为" + x);

把这段向十进制转换的代码放到else里就可以了

上一个:C#怎么网络编程呢?
下一个:C#的编程逻辑是什么

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,