第4关:十进制数转换为二进制数

任务描述

本关任务:编写程序实现十进制整数转化为二进制整数。要求十进制数从键盘输入,整数的范围为12147483647(2^31-1)

相关知识

为了完成本关任务,你需要掌握:1.数组的赋值与访问方法,2.十进制转化为二进制的方法。

程序分析

本任务需要定义一个数组,根据题意可知,数组大小应该为32个元素,因2147483647321

实现方法为,假设输入的整数为a,则当a <=0||a>2147483647,输出input error!

假设a在规定范围内,则使a循环除以2取余数,并将求出的余数依次存入数组,最后逆序输出即可。

数组声明语句如下:

int[] c = new int[32];//声明一个int型数组并动态初始化其大小为32

逆序输出数组

通俗的理解,逆序输出数组就是:把数组中的元素从下标最大值开始逆向输出到下标为0。

示例如下:

  1. int[] arr = {1,3,5,7,9};
  2. for(int i = 4; i>=0; i--){
  3. Console.WriteLine("{0}",arr[i]);
  4. }

输出:97531

编程要求

根据提示,在右侧编辑器补充代码,计算并输出转换后的二进制数。

测试说明

平台会对你编写的代码进行测试:

测试输入:

4

预期输出:

100

测试输入:

10

预期输出:

1010

测试输入:

1024

预期输出:

1000000000

测试输入:

-10

预期输出:

input error!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ch704
{
    class Program
    {
        static void Main(string[] args)
        {
			/******begin*******/
			int n = Convert.ToInt32(Console.ReadLine());
            if (n <= 0 || n > 2147483647)
            {
                Console.WriteLine("input error!");
                return;
            }
            Stack<int> s = new Stack<int>();
            while (n != 0)
            {
                s.Push(n % 2);
                n /= 2;
            }

            while (s.Count != 0)
            {
                Console.Write(s.Peek());
                s.Pop();
            }
            Console.WriteLine();
			
			
			/*******end********/

        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/mjn1/p/12452171.html