【发布时间】:2018-11-01 04:23:15
【问题描述】:
对于我的介绍。为了编程考试复习,我被要求编写一个程序,该程序使用一个函数来计算一组数字的 gcd。我编写了以下代码,有时似乎可以正常工作,但其他代码返回浮点异常 8。我希望有人能阐明一下。
我在使用 macOS High Sierra 的 mac 终端上使用 clang gcd.c -o gcd 进行了编译,返回 FP 错误的数字是 5372 18960 -230048 1185 16486
这是代码:
#include <stdio.h>
#include <stdlib.h>
int gcd(int a, int b){
if((a==0) || (b==0)){
return 0;
}else{
if( a % b == 0 ){
return b;
}else{
if ( b % a == 0 ){
return a;
}
}
}
while( (a != 0) && (b != 0) ){
if (abs(a)>abs(b)){
a = abs(a) % abs(b);
}
if(b>a){
b = abs(b) % abs(a);
}
}
if (a == 0){
return b;
}else{
return a;
}
}
int main(void){
int n;
printf("Please enter the number of integers in your array:\n");
scanf("%d", &n);
int a[n];
printf("Please enter the numbers in your arrray:\n");
for (int i = 0; i < n; ++i){
scanf("%d", &a[i]);
}
for (int i = 0; i < (n-1); ++i){
a[i] = gcd(a[i], a[i+1]);
}
printf("The gcd of the %d numbers is %d .\n", n, a[n-2]);
return 0;
}
【问题讨论】:
-
for (int i = 1; i <= n;我们又来了。假设 n==2。有多少个数字?第一个数字的索引是多少?最后一个数字的索引是多少?<=2的自然数是多少? -
@n.m 不错的收获。但即便如此,没有 FP 操作的程序抛出 FP 错误是相当疯狂的。会不会是一个解释器,它使用双精度来做 int 算术或类似的奇怪的东西? AlexD,您确实需要在此类问题中包含有关您环境的信息。
-
@Gene 除以零通常会导致 FP 错误,即使它是整数。
-
查看此代码
for (int i = 0; i < (n-1); ++i){ a[i] = gcd(a[i], a[i-1]); }第一次迭代时a[i-1]是什么? -
注意:
abs(INT_MIN)是 UB。不清楚gcd()中abs()的需要。