for循环中错位的分号 [英] Misplaced semicolon in for loop

查看:40
本文介绍了for循环中错位的分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做作业时,我犯了一个小错误,把 ;在 for 循环中,如以下代码.

When I am doing my assignments I done a small mistake by placing ; in the for loop like the following code.

for(i=0;i<n;i++);{
    n=n*i;
}

当我编译程序时,它编译没有错误,但我有一段时间没有得到输出.后来发现我在 for 循环中放错了分号.当我在 for 循环后放置分号时有什么错误.

When I compiled the program its compiled with no error but I did not get the output for a while. Then later figured out that I misplaced the semicolon in for loop. What was the bug when I place semicolon after for loop.

class A
{
    public static void main(String args[])
    {
        int i, n=1;
        for(i=1; i<=5; i++);
        n=n*i;
        System.out.println(n);
    }    
}

我得到以下代码的输出为 6 而不是 120.

I am getting output for the following code as 6 instead of 120.

推荐答案

如果将分号放在 for 循环之后,那么它在技术上是正确的语法.因为它被认为是一个空语句——这意味着没有什么可以执行的.

If you place semicolon after a for loop then it is technically correct syntax. Because it is considered as an empty statement - that means nothing to execute.

在你的情况下 -

for(i=0;i<n;i++);  

一个空语句最多执行 n 次.或者换句话说,for-loop 只运行 n 次.

An empty statement executed up to n times. Or in other words the for-loop simply runs n times.

for 循环后的花括号 {} 只执行一次.现在花括号 {} 内的代码块被视为 浮动块.

The curly braces {} after the for loop executed only once. Now the code block inside the curly braces {} considered as a floating block.

这篇关于for循环中错位的分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆