循环跳过偶数 [英] Do loop skipping even number

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

问题描述

I代表全局变量,即名称I代表函数内部和外部的相同变量.当I = 1时,首先调用事实,这是第一个写入的值.这个值是 传递给函数的伪参数N.Fact内的DO循环现在为相同的I赋予了初始值2,但由于它大于N,因此不会执行DO循环,因此我仍然具有值2 当事实返回要在主程序中打印时.但是,现在我在 主程序中的DO循环,它是第二次调用Fact时具有的值.

I represents the global variable i.e the name I represents same variable inside and outside the function. Fact is first called when I = 1, which is the first value written. This value is passed to the function's dummy argument N. The same I is now given the initial value 2 by the DO loop inside Fact, but since it is greater than N, the DO loop is not executed, so I still has the value 2 when Fact returns to be printed in the main program. However, I is now incremented to 3 in the DO loop in the main program, which is the value it has when the second call to Fact takes place.

PROGRAM Factorial 
IMPLICIT NONE 
INTEGER I

DO I = 1, 10 
PRINT*, I, Fact(I) 
END DO

 CONTAINS 
 FUNCTION Fact( N ) 
INTEGER Fact, N, Temp 
Temp = 1 
DO I = 2, N 
  Temp = I * Temp 
END DO 
Fact = Temp 
END FUNCTION 
 END

完成后,我从2转到N,现在N = 3.现在该函数必须将I = 3返回到主程序,以便下一个在主程序的Do循环中返回4,但是在编译并运行时..它仅显示3、5、7和9的因数....我的问题是为什么它跳过4或6或8.

and Once it completes I goes from 2 to N where now N =3..Now the function must returns I =3 to main program such that next I should be 4 in Do loop of main program, but when compiled and run..it only shows factor for 3,5,7 and 9.....My question is why it skip 4 or 6 or 8.

推荐答案

退出循环后,控制变量获取上限+ 1的值.但是,修改循环控制变量的值以及任何其他操作都是非法的如果在编译器进行检查的情况下仍设法做到这一点,则可能会发生这种情况.那就是未定义的行为.

After exiting a loop the control variable gets the value of the upper bound + 1. However, it is illegal to modify the value of a loop control variable and anything can happen if you manage to do that despite the compiler's checks. It is an undefined behaviour then.

不仅如此,还通过在函数中同时将I用作N来别名全局I.假定实际上它们引用相同的变量时它们是不同的,则编译器可能会执行各种优化.因此,该程序再次非法且不可预测.

Not only that, you are aliasing the global I by using it as I as N at the same time inside the function. The compiler can probably perform various optimizations assuming that they are distinct when in fact they refer to the same variable. The program is therefore again illegal and unpredictable.

请考虑以下示例,并尝试使用不同的优化级别对其进行编译.您将得到不同的答案:

Consider this example and try to compile it with different optimization levels. You will get different answers:

i = 1
call s(i)

contains

  subroutine s(j)
    do k = 1, 10
      j = i + j
    end do
    print *, j
  end
end

在线试玩!

可以通过声明i或伪参数target来解决此特定问题.

This particular problem can probably be fixed by declaring i or the dummy argument target.

这篇关于循环跳过偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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