I'm new to C (and mainly programming in general).
I'm trying to write a basic program to output the Taylor expansion of x = 1.5 from n = 1 to n = 100. My code is this:
#include <iostream>
int main() {
double x = 1.5;
double expx = 1;
double summand = 1;
for (int n=1; n <100; n) {
summand *= x/n;
expx = summand;
}
return expx
std::cout << "final expx from n = 1 to 100 is " << expx << std::endl;
}
When I run it, it runs without errors on terminal, but displays no output at all. I'm not quite sure what I'm doing wrong as when I run other code I've written, similar to this, I don't have a problem.
CodePudding user response:
What you should have done is create an expx() function and output the result of that.
#include <iostream>
double expx()
{
double x = 1.5;
double expx = 1.0;
double summand = 1.0;
for (int n=1; n <100; n)
{
summand *= x/n;
expx = summand;
}
return expx;
}
int main()
{
double value = expx();
std::cout << "final expx from n = 1 to 100 is " << value << std::endl;
}
CodePudding user response:
Anything that you write after a return statement inside a function won't execute. You need to switch the last two lines around, i.e:
std::cout << "final expx from n = 1 to 100 is " << expx << std::endl;
return expx