回 帖 发 新 帖 刷新版面

主题:[讨论]Fortran 判断奇偶数?

要判断一个整数是奇数还是偶数,用fortran如何编写?

回复列表 (共22个回复)

沙发

MOD

Elemental Intrinsic Function (Generic): Returns the remainder when the first argument is divided by the second argument.

Syntax
result = MOD (a, p)

a
 (Input) Must be of type integer or real. 
 
p
 (Input)Must have the same type and kind parameters as a.
 

Results
The result type is the same as a. If p is not equal to zero, the value of the result is a- INT( a/ p) * p. If p is equal to zero, the result is undefined.

板凳

if(a/2.0==a/2) Then
偶数
else
奇数
endif

3 楼

2 楼: 您这个条件判断的“代价”可不小呀。

4 楼

只要a是整型数据的话应该没有问题,这个我在电脑上测试了,不知道是不是与电脑有关。
如果a是实型的话就会出问题
[color=FF0000]也许下面的写法会好一些
if(abs(a/2.0-int(a/2))<=0.01) Then
   write(*,*) "偶数"
else
   write(*,*) "奇数"
endif[/color]

5 楼

HOHO,您应该看看 整数 的定义了。既然楼主说了是整型数据,您 4 楼 提供的代码没有任何意义,不要把简单问题搞复杂了。

6 楼

[quote]2 楼: 您这个条件判断的“代价”可不小呀。[/quote]
那我的代码有什么“代价”??请赐教!

7 楼

就您在 2 楼提供的语句:   if(a/2.0==a/2) Then
有如下过程:
1。  a / 2.0 首先 整型数据 a (楼主明确说了 a 为整数)“promotion”到单精度(默认情况下),再做浮点数除法;   
2。 a / 2 为整数相除,值为整数;
3。 A relational expression can compare two numeric expressions of different data types. In this case, the value of the expression with the lower-ranking data type is converted to the higher-ranking data type before the comparison is made.
也就是说,后面的整数要转换为单精度浮点数,在执行 == 
4。 浮点数比较还是要注意的,您在 4 楼已经注意了,不过 后面的 0.01 似乎换为 比 epsilon(1.0) 稍大的数似乎更佳。 

其实,只要一个很简单的语句 if ( mod(a, 2) == 0 ) then 就可以了。

8 楼

谢谢,我的计算时间差不多是你的一倍,以前没有考虑这个问题
谢谢指教。

9 楼

谢谢各位的讨论。受益匪浅。

正如各位讨论的,如果输入的数据不一定是整数的时候如何判断呢?如果的是实型小数点后有数据的话,就没有奇偶之分了,也就是说如何将这种情况的数据挑出来呢?

10 楼

方法1:
先取小数部分如果不为0则处理之
方法2:
将数据转成整型再转回实型,然后做比较,在误差范围内不同则处理之:)

我来回复

您尚未登录,请登录后再回复。点此登录或注册