Where is the bug in my polynomial calculation code?
my aim is to compare the two different method to calculate a polynomial.. but if you run it on a mac (my computer is MacBook Air) you will find the two results are different... .but.... if you delete the "/* ... */" part OR delete the two "//" before "for ..." it works fine...
plus..it works fine on linux...
can anyone tell me why?..
here is my program:
#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;
}
You are accessing memory that is out of bounds of the array you create in main
and use in the other functions. This happens in at least three places.
The loop bounds in
normal_method
go from zero to ten:for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds
On the first line of
horner_method
you are accessing memory that is out of bounds of your array:test_type s = a[degree]; // a[degree] is out of bounds
The loop bounds in
generate_data
are incorrect the same way as innormal_method
:for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds
You shouldn't use %lf
to print a double
. Just %f
is fine. You probably confused that with scanf
, which needs the l
.
With the compiler warning options -Wall -Wextra -Wformat=2
gcc should tell you what's wrong in your code.
精彩评论