C - explicit integral as a parameter
I am counting approximation of Pi, I have made it to 3,14596
, but I have tried to set integral for counting pi as a parameter when starting program and no result came from it. I tried add when starting program 4/1+x*x
(there should by brackets around 1+x*x
, but compilator sees them as a mistake), and I get it from args[1
] as a 4 only when I transfered char to int with itoa()
. Is there any way how to pass it to application for computing? This is the line in my program:
float sum, integral;
integral=4/(1+x*x);
sum=sum+integral;
And I have it in for loop. In this case it counts great, but how to incorporate theese parameter?I have thought of some specific char replacement (I would 开发者_如何学Goreplace X for an actual value), but is it possible?
You can't pass the formula as argument of your program. Your arg[1]
parameter is a string, when you call atoi
you make only the conversion of the numbers up to the first nun numeric character, so in your case it converted the '4' character of your string "4/1+x*x"
and stopped conversion at the '/'.
If you want to use the formula, you have to write an interpreter that analyzes the string, builds an evaluation tree and execute by replacing the values of the variables. Something quite complicated, probably not under several hundred lines of code.
It's probably easier to use the formula in the source code and recompile the program accordingly. If it's not possible, change to an interpreted language like perl, python, javascript which implement the eval
function.
精彩评论