Last active
August 29, 2015 14:17
-
-
Save haskellcamargo/a9176ab8f6d0920814dc to your computer and use it in GitHub Desktop.
Ajuda APDA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author: Marcelo Camargo | |
* @license: GNU/GPL v3 | |
* @description: 1 + 1/2! + 1/3! ... 1/n! | |
*/ | |
#include <stdio.h> | |
#define EXIT_SUCCESS 0 | |
// Trabalhamos de forma recursiva para obter o fatorial de um | |
// número. O fatorial é matemática determinado por | |
// f(n) = n == 0 => 1 | |
// = n <> 0 => n * f(n - 1) | |
// de modo que, ao chegar a zero, multiplique por um. | |
// 3! = 3 * 2 * 1 * 1 [edge case] = 6. | |
double fact(int n) { | |
if (n == 0) | |
return 1; | |
else | |
return n * fact(n - 1); | |
} | |
// O exercício pede 1 + 1/2! + 1/3! ... 1/n! | |
// Já temos o fatorial definido, então, iniciando em 2, | |
// como proposto, até n, dizemos que e = e + 1/i! | |
double answer(int n) { | |
int i; | |
double e = 1.0; | |
for (i = 2; i <= n; i++) | |
e += 1 / fact(i); | |
return e; | |
} | |
// Perguntamos ao usuário por um valor inteiro e chamamos | |
// nossa função de resposta. Em scanf, passamos a referência | |
// da variável para que nela seja armazenado o valor. | |
// No final, retornamos EXIT_SUCCESS para evitarmos | |
// undefined behaviour. | |
int main(int argc, char** argv) { | |
int val; | |
printf("What value?\n"); | |
scanf("%d", &val); | |
printf("Answer: %f\n", answer(val)); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment