首页 文章

新的C#程序员困惑不解 . 很简单的程序 . 将int转换为字节格式,它可以工作,但不像我预期的那样

提问于
浏览
2

这是练习的措辞 .

**创建一个控制台应用程序,询问用户0-255范围内的两个数字,然后将第一个数字除以第二个数字:

输入0到255之间的数字:100

输入0到255之间的另一个数字:8

100除以8是12

编写异常处理程序以捕获任何抛出的错误:

输入0到255之间的数字:apples

输入0到255之间的另一个数字:香蕉

FormatException:输入字符串的格式不正确 . **

这是我写的程序,它的工作原理 . 但我的意图是通过写 byte result = divisor / dividend; 来缩短它

除数和被除数都已经作为一个字节被转换,为什么我不能直接在代码中使用它们呢?

I had to calculate the operation using an int and then cast that int into a byte . (2步而不是一步,令我困惑)

我错过了什么吗?

static void Main(string[] args)
    {
        checked
        {
            try
            {
                WriteLine("Enter a number between 0 and 255");
                string firstNumber = ReadLine();
                byte divisor = Convert.ToByte(firstNumber);
                WriteLine("Enter another between 0 and 255");
                string secondNumber = ReadLine();
                byte dividend = Convert.ToByte(secondNumber);
                int calculation = divisor / dividend;
                byte result = Convert.ToByte(calculation);
                WriteLine($"The result of the division between {divisor} and {dividend} is {result}");
            }
            catch (OverflowException)
            {
                WriteLine("The number you entered is either lower than 0 or superior to 255, please enter a number between 0 and 255");
            }
            catch (FormatException)
            {
                WriteLine("You didn't enter a number");
            }
            catch (Exception ex)
            {
                WriteLine($"{ex.GetType()} says {ex.Message}");
            }
        }

        ReadKey();
    }

2 回答

  • 1

    这是因为 byte 没有定义任何算术运算符 .

    divisor / dividend 的代码相当于 (int)divisor / (int)dividend ,这就是为什么在尝试将结果存储在_619668中时会出错的原因 .

    你正在做的是正确的,或者写作 byte calculation = (byte)(divisor / dividend);

  • 0

    你可以施展它:

    byte calculation = (byte)(divisor / dividend);
    

    有关详细信息,请参阅此链接:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/byte

相关问题