a problem with my C code

ROG 21 Reputation points
2020-12-03T10:52:12.137+00:00

i got a problem with this code,

not sure what's the problem
would appreciate the help.

void Ex5()
{
double x, ans;
int n;
printf("Enter a real number >>> ");
scanf_s("%lf", &x);
printf("Enter a natural number >>> ");
scanf_s("%d", &n);
ans = f5(n, x);
printf("%.3lf\n", ans);

}
double f5(int n, double x)
{
double num, den, r, i = 2, sum = x - 1;
int p = 3;
while (p <= (2*n + 1))
{
den = ((factorial(p))*i);
r = x - 1;
num = pow(r, p);
sum += (num / den);
p += 2;
i++;
}

}
long factorial(int n)
{
long factor = 1, j;
for (j = 1; j <= n; j++)
factor *= j;
return factor;
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,537 questions
0 comments No comments
{count} votes

Accepted answer
  1. Guido Franzke 2,196 Reputation points
    2020-12-03T11:08:02.587+00:00

    Hello,
    it looks like you are writing 32 bit code. Then long is 4 byte and double is 8 byte.
    Look at your operation:

    den = ((factorial(p))*i);
    

    -> double = long * int

    i will be converted to long. The result of the multiplication will be long again. Then you cast it to 8 byte double.
    "long * long" can easily overflow. The compiler recognizes that you cast the result to 8 byte double, so that's why the compiler warns you.

    Use this coding instead:

    den = (double)factorial(p) * i;
    

    -> long and int will be casted to double first. The multiplication will now operate on 8 byte doubles instead of 4 byte longs.

    Regards, Guido


0 additional answers

Sort by: Most helpful