2011-09-27 63 views
0

我的目的是比较两种不同的方法来计算一个多项式。但是如果你在Mac上运行它(我的电脑是MacBook Air) 你会发现两个结果是不同的... 。但.. .. 如果删除“/ * ... * /”部分或删除之前的两个“//”为“...” 它工作正常...我的多项式计算代码中的错误在哪里?

plus..it正常工作Linux的...

谁能告诉我为什么..

这里是我的程序:

#define MAX_NUM 10 
#define TEST_TIME 1 
#define test_type double 

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

test_type normal_method(test_type *a, test_type x, int degree) 
{ 
    test_type s = 0.0; 
    test_type e = 1.0; 

    for (int i = 0; i <= degree; i++) { 
     s += a[i] * e; 
     e *= x; 
    } 

    printf("%lf\n", s); 

    return s; 
} 

test_type horner_method(test_type *a, test_type x, int degree) 
{ 
    test_type s = a[degree]; 

    for (int i = degree - 1; i >= 0; i--) { 
     s *= x; 
     s += a[i]; 
    } 

    printf("%lf\n", s); 

    return s; 
} 

void generate_data(test_type *a, test_type *x, int degree) 
{ 
    srand(time(NULL)); 
    for (int i = 0; i <= degree; i++) { 
     a[i] = (test_type)(rand() % MAX_NUM + 1)/(test_type)(rand() % MAX_NUM + 1); 
     *x = (test_type)(rand() % MAX_NUM + 1)/(test_type)(rand() % MAX_NUM + 1); 
    } 

} 

int main() 
{ 
    const int degree = 10; 
    test_type a[degree]; 
    test_type x; 

    generate_data(a, &x, degree); 

//Just by clear the /**/ below, the program will work fine.... 
/*  
    printf("x = %lf\n", x); 
    for (int i = 0; i <= degree; i++) { 
     printf("%lf\n", a[i]); 
    } 
*/ 
    clock_t begin, end; 

// Or clear the two // below, it will work fine too.... 

    begin = clock(); 
// for (int i = 0; i < TEST_TIME; i++) 
     normal_method(a, x, degree); 
    end = clock(); 
    printf("The normal method used %d clock times\n", end - begin); 

    begin = clock(); 
// for (int i = 0; i < TEST_TIME; i++) 
     horner_method(a, x, degree); 
    end = clock(); 
    printf("The horner method used %d clock times\n", end - begin); 

    return 0; 
} 
+2

首先它不是一个惊人的问题。其次,在代码说没有足够的代码上下文之前,巨型评论块是什么。 –

+0

是的,这个问题最好称为“程序更改行为,当我删除评论”。 –

+2

您还可以定义一个容量为10的数组,但稍后将其写入索引10(这是第11个元素)。 –

回答

0

您不应该使用%lf来打印double。只是%f是好的。您可能会与scanf混淆,这需要l

使用编译器警告选项-Wall -Wextra -Wformat=2 gcc应该告诉你代码中有什么问题。

5

您正在访问的存储器超出了您在main中创建的阵列的范围,并在其他功能中使用。这发生在至少三个地方。

  • normal_method循环边界去从0到10:

    for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds 
    
  • horner_method您正在访问内存中的第一行是你的数组的边界:

    test_type s = a[degree]; // a[degree] is out of bounds 
    
  • generate_data中的循环边界与normal_method中的方式不正确:

    for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds 
    
+1

'generate_data'还写入了11个元素(“'i <= degree'”)。 –

+0

好的。我会更新答案以补充。 'normal_method'中的循环边界同样是不正确的。 –