c#中简单的for循环

本文关键字:for 循环 简单 | 更新日期: 2023-09-27 18:05:38

我正在尝试使用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);
            }
        }
    }
}

只是为了测试我是否能得到任何输出。我不确定这是否是解决这个问题的最好方法。控制台窗口只打开一秒钟,然后消失。我该如何解决这个问题?

c#中简单的for循环

您可以使用Console.ReadKey()修复它。通常情况下,在主机应用中就会出现这种情况(虽然我不建议你这么做,如果你能做到的话)。控制台倾向于从现有的命令行运行,并期望在完成后立即退出(返回到终端的上下文),您将看到如下内容:

Console.WriteLine("press any key to exit...");
Console.ReadKey();

try

Console.ReadKey();

循环后

您也可以尝试使用ReadLine method

Console.ReadLine();

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

您可以在最后一行设置一个断点以便调试器停止,添加一个类似ReadLine的调用以便需要用户输入,添加一个延迟(Sleep)以便Windows保持显示几秒钟或从命令提示符运行。

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

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

  2. 对我来说,使用调试器做到这一点的最佳方法是在main方法的右括号中添加一个断点(F9)。

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

Ctrl + F5将留下一个Press any key to continue...,这将阻止控制台自动关闭。

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

此解决方案将防止向项目中添加代码。

这里是其他人提到的所有更改的干净代码。主要是模(见%)和控制台。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();
        }
    }
}

操作太多

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

就像别人说的,

 Console.ReadKey()

将让您看到结果。