如何格式化我的程序以显示所有1? [英] How do I format my program to display all the 1's ?

查看:44
本文介绍了如何格式化我的程序以显示所有1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我编写了一个算法,将十进制数转换为二进制数,不使用数组,字符串连接和其他命名空间(系统除外)。

我得到了正确的结果代码但由于某种原因,当整数变大时,它会舍入值。我测试了最大数字uint可以采取的是4294967296,我的输出应该是1 ....(32次)。



有人可以帮我这里?



Okay, So I have written an algorithm to convert decimal numbers to binary numbers, without using arrays, string concatenation and other namespaces( other than System ).
I am getting the correct result for my code but for some reason it rounds off values when the integer gets big. I tested for the biggest number uint can take which is 4294967296, and my output should be 1....(32 times).

Can someone help me out here?

using System;

class Binary
{
    public static void Main( )
    {
        Console.WriteLine( "Binary Encoder" );
        Console.WriteLine( );



        Console.Write( "Enter an unsigned integer number: " );
        uint integer = uint.Parse(Console.ReadLine());
        double number = integer;


        double temp = 0;
        double counter = 0;



        while( integer > 0 )
        {
            if( integer % 2 == 1 )
            {
                temp =  temp + Math.Pow( 10, counter );
                Console.WriteLine(temp);
            }

            counter++;
            integer = integer / 2;
        }

        Console.WriteLine("The binary encoding of {0} is: {1:F0}",number,temp);



    }
}

推荐答案

很棒的练习。这让我想起了我的第一台计算机和机器语言编程的第一步。我还需要一些练习,只需在旧计算机上用机器语言实现它。



由于内存中表示双精度的方式,你正在遇到舍入错误。我没有分析过哪里出错了,但是双精度(以及浮点数)不能代表具有无限精度的每个数字,在任何时间间隔内精度至少也不会是同质的。



您的解决方案很好,但不需要转换为double。看一下移位运算符(<<>>)。在原始uint上使用这些,并记住它们等于整数除法或乘以2的幂乘,取决于班次的方向和班次的数量。



在这里我发现了一个小扰流板,万一你不能让它工作: http://www.dotnetperls.com/转移 [ ^ ]
Nice exercise. It made me think of my first computer and my first steps in machine language programming. And I also needed some exercise and just implemented it in machine language on the old computer.

You are running into rounding errors due to the way doubles are represented in memory. I have not analyzed where exectly things go wrong, but doubles (as well as floats) cannot represent every number with infinite precision, nor will the precision at least be homogenous over any interval.

Your solution is good, but the conversion to double is not needed. Take a look at shift operators (<< and >>). Use these on the original uint and keep in mind that they are equivalent to integer divisions or multiplications by powers of 2, depending on the direction of the shift and the number of shifts.

And here I found a little spoiler, in case you don't get it to work: http://www.dotnetperls.com/shift[^]


这篇关于如何格式化我的程序以显示所有1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆