为什么我的代码不打印任何结果?

时间:2018-04-16 14:24:25

标签: c#

我基本上要做的是使用2语句减去添加 switch个数字。我知道我不能更有效率地做到这一点,但我还没有进入那些东西(因为我用谷歌搜索我将如何做到这一点,它有很多不同的经验方法)。
我提出了以下一段代码,我在微软的网站和一些谷歌的东西上使用了一些参考资料。

但是我不能让它起作用,它在某种程度上有效,但它从来没有给我答案。

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Type number 1: ");
            int line1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("Type number 2: ");
            int line2 = Convert.ToInt16(Console.ReadLine());

            Console.WriteLine("1 = +");
            Console.WriteLine("2 = -");
            int formula = Convert.ToInt16(Console.ReadLine());
            switch (formula)
            {
                case 1:
                    Console.WriteLine("Answer is ", (line1 + line2));
                    break;
                case 2:
                    Console.WriteLine("Answer is ", (line1 - line2));
                    break;
                default:
                    Console.WriteLine("Choose 1 or 2");
                    break;
            }
            Console.ReadLine();
        }
    }
}

当我运行它时,它只显示

"Answer is "

哪里出错了?

4 个答案:

答案 0 :(得分:6)

添加格式,即 {0},其中包含系统应该回答的字符串:

Console.WriteLine("Answer is {0}", (line1 + line2));

...

Console.WriteLine("Answer is {0}", (line1 - line2));

答案 1 :(得分:3)

您没有指定应在格式字符串中插入值的位置。现在你的价值被忽略了。您可以通过多种方式完成此任务:

Console.WriteLine("Answer is {0}", (line1 + line2));

{0}表示应插入第一个参数的位置。 (所以下一个是{1}等等。)

C#6,有点安全:

Console.WriteLine($"Answer is {line1 + line2}");

答案 2 :(得分:1)

你可以写

Console.WriteLine(“答案是{0}”,(第1行+第2行));

或(不太漂亮)

Console.WriteLine(“答案是”+(第1行+第2行)); //如果你在第一部分没有字符串,我不推荐后者 但是一个int它可能只是添加它们取决于你如何编写..

答案 3 :(得分:0)

你需要知道在哪里插入你的第二个参数,你的字符串

Console.WriteLine("Answer is {0}", (line1 + line2));

这告诉Console.WriteLine在您放置“{0}”的位置插入第一个参数。 使用更多参数,您需要增加索引,即

Console.WriteLine("Answer is {0} {1}", "not", "here"); //displays "Answer is not here"

MSDN。 另一个提示:所有参数都自动转换为字符串,因此您无需手动转换它们。

相关问题