user21000968
user21000968

Reputation: 1

why does the value of this factorial change when called by a function that SHOULD calculate the value of e

#include <stdio.h>
#include <math.h>

int main()
{
    double precision = 0;
    printf("\ninsert number\n");
    while(precision < 1){
        scanf("%lf",&precision);
    }
    printf("the value of e with precision of %.0lf is %lf",precision,e(precision));
    return 0;
}

int fact(int num){
    int ris = 1;
    for(int i = num;i > 0;i--){
        ris = ris * i;
    }
    printf("res=%d\n",ris);
    return ris;
}

int e(double precision){
    double valE = 1;
    for(double i = precision;i > 0 ;i--){
        valE = valE + 1/fact(i);
        printf("\nsame res:%.1lf\n",fact(i));
    }
    return (double)valE;
}

debug

i know there is an answer for that but my problem is the comunication between the 2 functions, i know i could solve it by slapping everything inside the main()

Upvotes: 0

Views: 65

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50883

There are many issues:

  • format specifiers (for scanf and printf) must match the arguments
  • don't use floating point types as counters
  • if you divide one integer by another integer, the result will be an integer that is trucated. If you want the result to be a floating point type, you need to convert at least one of the operands to a floating point type.
  • you need to declare the functions you use (fact and e) before using them, or just put them before main, like below.

You want this, explanations in the comments:

#include <stdio.h>
#include <math.h>

int fact(int num) {
  int ris = 1;
  for (int i = num; i > 0; i--) {
    ris = ris * i;
  }
  printf("res=%d\n", ris);
  return ris;
}

double e(int precision) {
  double valE = 1;
  for (int i = precision; i > 0; i--) {  // use int for loop counters
    valE = valE + 1.0 / fact(i);         // use `1.0` instead of `1`, otherwise an 
                                         // integer division will be performed
    printf("\nsame res: %d\n", fact(i)); // use %d for int^, not %llf
  }
  return valE;                           // (double) cast is useless
}

// put both functions e and fact before main, so they are no longer
// declared implicitely

int main()
{
  int precision = 0;                  // precision should be an int
  printf("\ninsert number\n");
  while (precision < 1) {
    scanf("%d", &precision);          // use %d for int
  }
  printf("the value of e with precision of %d is %lf", precision, e(precision));
  return 0;
}

Upvotes: 3

Related Questions