1

我正在尝试使用 Visual C# Express解决http://projecteuler.net/problem=1 。

我创建了一个控制台应用程序并编写了以下代码:

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

namespace Euler_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 0;
            int sum = 0;
            for (int i = 0; i <= 10; i++)
            {
                if (num / 3 == 0)
                    sum = sum + num;
                num++;
                System.Console.WriteLine(num);
            }

        }
    }
}

只是为了测试我是否可以获得任何输出。我不确定这是否是解决此问题的最佳方法。控制台窗口只打开一秒钟然后消失。我怎样才能解决这个问题?

4

8 回答 8

3

您可以使用Console.ReadKey(). 通常,在发生这种情况的控制台应用程序中(尽管如果您能提供帮助,我绝不会推荐它......控制台往往从现有的命令行运行,并且预计在完成后立即退出,回到终端的上下文),您会看到如下内容:

Console.WriteLine("press any key to exit...");
Console.ReadKey();
于 2013-03-25T16:28:39.133 回答
2

你也可以试试ReadLine method

Console.ReadLine();

链接:http: //msdn.microsoft.com/fr-fr/library/system.console.readline.aspx

于 2013-03-25T16:34:58.697 回答
2

尝试

Console.ReadKey();

循环之后

于 2013-03-25T16:29:46.120 回答
0

Ctrl + F5 将为您留下 aPress any key to continue...这将阻止控制台自动关闭。

或者,您可以转到Debug工具栏中的 并单击Start Without Debugging

此解决方案将阻止向您的项目添加代码。

于 2013-03-25T16:47:22.747 回答
0

操作太多

if (i / 3 == 0)
   sum+=i;

正如其他人所说,

 Console.ReadKey()

会让你看到结果。

于 2013-03-25T16:34:31.587 回答
0

您可以在最后一行放置断点以便调试器停止,添加像 ReadLine 这样的调用以便需要用户输入,添加延迟(睡眠)以便 Windows 保持显示几秒钟或从命令提示符运行它.

于 2013-03-25T16:33:50.727 回答
0

问题是应用程序在循环完成后终止(控制台关闭)。要保持控制台打开,您可以执行以下操作之一:

  1. 如果您通过按ctrl+F5而不是 just 来启动没有调试器的应用程序F5,您将Press any key to continue . . .在程序退出之前看到 a 。

  2. 对我来说,使用调试器执行此操作的最佳方法是F9在方法的右括号中添加断点 () main

添加额外的代码来帮助您调试程序对我来说是个坏习惯。

于 2013-03-25T16:37:36.007 回答
0

这里是干净的代码以及其他人提到的所有更改。主要是取模(见 %)和 Console.ReadKey

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

namespace Euler
{
    class Program
    {
        static void Main(string[] args)
        {
            const int max = 10;
            int sum = 0;

            for (int i = 0; i < max; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                    sum += i;
            }

            Console.WriteLine("The sum of all multiples of 3 and 5 from 0 to {0} is: {1}", max, sum);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
于 2013-03-25T16:56:38.113 回答