C#:乘法身份,我如何做到这一点?

时间:2014-10-04 16:11:18

标签: c#

A ^ 2-B ^ 2 =(A-B)*(A + B)是我所拥有的论坛。

用户应该输入A和B.

假设我把A设为4,B设为2. A = 4,B = 2。 如何让它在我的输出屏幕上显示如下? :

4 ^ 2 - 2 ^ 2 =(4-2)*(4 + 2)

16-4 =(2)*(6)

12 = 12

1 个答案:

答案 0 :(得分:0)

首先,你的问题似乎有一个拼写错误。显然你的公式不是A^2-B^2=(A-B)+(A+B),正如你问题的开头所暗示的那样;显示的例子是在等式的右边进行乘法运算。

以下是如何执行此操作的一个非常基本的示例。

int a = ReadInt("Enter value for A: "); // see end of answer for `ReadInt` definitions
int b = ReadInt("Enter value for B: ");

Console.WriteLine("{0}^2-{1}^2=({0}-{1})*({0}+{1})", a, b);
Console.WriteLine("{0}-{1} = ({2})*({3})", a * a, b * b, a - b, a + b);
Console.WriteLine("{0} = {1}", a * a - b * b, (a - b) * (a + b));

输出文本中的{0}{1}等是占位符。它们在MSDN文章"Composite Formatting"中进行了解释。基本上,大括号内的从零开始的数字指定格式文本(Console.WriteLine的第一个参数)之后的哪些参数将被打印出来。

上面的代码引用了一些ReadInt方法。以下是两种可能的定义:

  • 不安全的非验证变体,如果用户输入的不是范围内的整数,则会抛出异常:

    static int ReadInt(string prompt)
    {
        Console.Write(prompt);
        return int.Parse(Console.ReadLine());
    }
    
  • 更安全,验证变体:

    static int ReadInt(string prompt)
    {
        for (;;)
        {
            Console.Write(prompt);
            int result;
            if (int.TryParse(Console.ReadLine(), out result))
            {
                return result;
            }
            else
            {
                Console.WriteLine("Invalid input! Please enter an integral number.");
            }
        }
    }