EDIT: it seems that this code snippet works, but in visual studio it doesn’t work, i don’t know why
this program takes a command line argument "c" and it has to approximate pi using the recursive formula,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double pi(double c) {
if (c == 0) {
return 4;
}
double k = ((4 * pow(-1, c)) / (2 * c + 1));
return k + pi(c - 1);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
return 1;
}
double c = strtod(argv[1], NULL);
if (c < 0) {
return 1;
}
double result = pi(c);
printf("%lf", result);
return 0;
}
I can’t find the error, when I debug it, program exits with code 1 even if I use c = 10.
2
Answers
The code snippet works, as can be shown in this online compiler: Live demo
For 10 iterations, the result it gives is:
When you launch the executable in Visual Studio, by default, it launches without arguments. That makes your first check fail (
(argc != 2)
) and return 1.You need to specify arguments to be passed to your executable in project settings (project properties -> debugging section -> command arguments)
The code itself works fine.