-2

If i enter a value lets say "3" i get a result of 0. Please explain why and if there is a way please show me. Should I use float?

#include <stdio.h>
int getResult (int nVal)
int c , f;
int nExp;
double dSum;
f = 1;
dSum = 0;

nExp = nVal;
for (c = 1; c <= nVal; c++)
{
    f = f * c;
    dSum += f / nExp;
    nExp = nExp * nVal;
}

return  dSum;
int main ()
{

int nVal, nCompute;
double dSum;
printf("Enter Number to be Computed");
scanf("%d",&nVal);

nCompute = getResult (nVal);

printf("%d", nCompute);

return 0;   
}

1 Answers1

2

f and nExp are ints, so you're dividing them using integer division, keeping only the "whole" part of the result, to the left of the decimal point, which is zero. Instead, you define one or both of them as doubles, so you'd be performing floating-point division.

Mureinik
  • 297,002
  • 52
  • 306
  • 350