I fixed your code step by step, I can't go further because I'm not sure what you want to do in your code. If you tell us what they are, I'll be able to fix this code.
#include <iostream>
#include <iomanip>
#include <stdio.h>
int main() {
long double x,term,fx, fact;
int i, j, nterms;
int sign;
std::cin>>x>>nterms;
term=1;
fact=1;
sign=1;
fx = 0;
for(i=1;i<=nterms;i+=2){
for(j=1;j<=i;j++){
term=term*x;
fact=fact*j;
}
sign=-1*sign;
fx+=sign*term/fact;
}
std::cout << std::setprecision( 6 ) << fx << std::endl;
}
Some remarks here:
It seems that using namespace
was used for std
. Use it carefully, since a conflict between some namespaces could occur. This page (french) suggest two use case.
a. Importing the symbols one by one:
using std::cout;
using std::endl;
b. Use them only in a local scope (in a curly brace block for example):
void a_function() {
// std will be imported only within this block
using namespace std;
cout << "hello there" << endl; // will work
}
Declare your variables before using them. Compare my answer with your code sample.
- Be careful with the min and max values a type can handle. Your function seems to handle very huge or small values. I changed their type to long double (but it's just moving the issue further). You have the ranges. Have a look this SO answer. It leads to limit.h, which shows numeric limits. Pick the safest to store your values (or sets a max and min value for user inputs).