#include<stdio.h>
int main()
{
int i,n=5;
for(i=0;i<n;i++)
{
printf("in of loop the value of i is %d\n",i);
}
printf("out of loop the value of i is %d",i);
}
我无法理解为什么i的值在循环外显示为5,但在循环中i的最后一个值是4。
答案 0 :(得分:2)
for循环在指令块的末尾递增i的值。因此,当i = 4时,循环运行但最后,i = 4 + 1 = 5.此时,循环中的条件不再满足,因为我现在等于5。
答案 1 :(得分:1)
你可以看到for循环是一个伪装的while循环:
package ee.forum.ejb.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(schema = "FORUM", name = "POST")
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(
name = "POST_ID_GENERATOR",
sequenceName = "SEQ_POST",
schema = "FORUM",
allocationSize = 1,
initialValue = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "POST_ID_GENERATOR"
)
private Long id;
@NotNull
@Size(min = 5, max = 1000)
private String text;
@NotNull
@ManyToOne
private Thread thread;
@NotNull
@ManyToOne
private User author;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date created;
public Post() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
相当于
for(i=0;i<5;i++)
{
do stuff;
}
所以最后,i = 5
答案 2 :(得分:1)
在循环中,i的最后一个值是4,然后是i ++,我是5,i
答案 3 :(得分:0)
如果你想执行for循环5的主体 你只需考虑做以下修正:
for(i=0; i<=n; i++){
/*
The code here will be executed 5 times.
Subsequently the last printed value will be 5.
*/
printf("in of loop the value of i is %d\n",i);
}
您观察到的是由于n的值与被评估为进入for循环的条件不匹配。执行五次for 周期n应小于或等于为5.
在这种情况下:
for(i=0; i<n; i++) {
printf("in of loop the value of i is %d\n",i);
}
当n等于5时,它不满足进入for循环的要求。这里的条件是“如果n小于5,则输入循环”,但如果n小于或等于5则不认为是这种情况。
如果您希望执行循环5次,只需使用关系运算符“&lt; =”。