c# - 为什么在最内层的 for 循环中添加大括号会产生如此奇怪的结果?

标签 c#

这是我对我在这里提出的上一个问题的稍微修改过的答案。当发生奇怪的事情时,我正在更改它以更好地理解它。

C# 中的 For 循环应该以这种方式工作:

for (initial increment value, end increment value, increment rate)
{
    // for loop body
}

我得到的答案代码似乎有效,但最内层的 for 循环没有大括号。这是代码:

using System;

class Prime_Screening
{
    static void Main()
    {
        Console.WriteLine("Prime numbers x, where: 0 < x < 100");
        bool prime;

        for (int num = 2; num <= 100; num++)
        {
            prime = true; /


            for (int div = 2; div <= Math.Sqrt(num); div++)
            // Why isn't the contents of this for loop in braces? Attempting it produces a weird output
                if(num % div == 0) 
                    prime = false;
                if (prime) 
                    Console.Write(num.ToString() + ", ");
        }
    } 
}

我在那个 for 循环中添加了大括号,这样我就可以保持代码清晰,但是我得到了一些奇怪的重复输出:

5, 7, 9. 11, 11, 13, 13, 15, 17, 17, 17, 19, 19, 19, 21, 23, 23, 23, 25, 25, 25, 27, 29, 29 , 29, 29, 31... 93, 95, 95, 95, 97, 97, 97, 97, 97, 97, 97, 97, 99,

为什么?当我们讨论这个主题时,if 语句也应该放在大括号中吗?

编辑:拼写/语法

最佳答案

您不需要使用大括号,但只有第一个语句属于循环。

因为这里不是 if-else 而是两个 if 只有第一个属于循环:

for (int div = 2; div <= Math.Sqrt(num); div++)
    if (num % div == 0)
        prime = false;
    if (prime)
        Console.Write(num.ToString() + ", ");

这等同于:

for (int div = 2; div <= Math.Sqrt(num); div++)
{
    if (num % div == 0)
        prime = false;
}
if (prime)
    Console.Write(num.ToString() + ", ");

与此代码相反,两者都属于循环:

for (int div = 2; div <= Math.Sqrt(num); div++)
{
    if (num % div == 0)
        prime = false;
    if (prime)
        Console.Write(num.ToString() + ", ");
}

来自 msdn:for-loop

The body of the loop consists of a statement, an empty statement, or a block of statements, which you create by enclosing zero or more statements in braces.

关于c# - 为什么在最内层的 for 循环中添加大括号会产生如此奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575861/

相关文章:

c# - 尝试创建嵌套的 ScriptableObject : "AddAssetToSameFile failed because the other asset is not persistent"

c# - 如果参数为 null,则阻止 MVC Action 方法执行

c# - 如何将字符串数组更改为不使用循环子句的字符串?可以用LINQ实现吗?

c# - 从存储过程中获取 bool 或 int 结果

c# - 如何从自动生成 gridview 列的 excel 中保存我的数据?

c# - 通过 css 或 jquery/c# 设置图像大小

c# - 在 C# 中将委托(delegate)转换为通用委托(delegate)

c# - 在 WPF 中使用矢量图形作为图标

c# - C# 中的 IObserver 和 IObservable 用于观察者与委托(delegate)、事件

c# - 来自其他 aspx 文件的 Response.WriteFile