I am trying to get a integration program running but I keep getting the nan when computing. i have no idea whats wrong with my code.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
cout << "For integration up \n";
for (int z=0; z<=5; z++){
int i=1;
float nathan [6] = {pow(10,2), pow(10,3), pow(10,4), pow(10,5),pow(10,6), pow(10,7)};
int h= nathan[z];
int n=0;
double x= (h-i)/h;
double y= (h-i)/h;
double t= 0;
while(n <= h){
if(n == 0){
t += (x/3)*(1/y);
}else if(n==h){
t+= (x/3)*(1/y);
}else if(n%2 ==1){
t+= (4*x/3)*(1/y);
}else{t+= (2*x/3)*(1/y);
}
y= x+y;
n = n+1;
}
cout << "The integration of 1/x for N = "<< nathan[z] <<" is equal to " << t << endl;
}
}
can someone please help me out with this...
it s because x and y are always 0 in your code because h is int. When you do (h-i)/h, the compiler assumes that (h-i) is int and h is also int so it also assumes that the result of the ratio is int. This ratio is between 0 and 1 so when you only represent it with an int, it is just 0. And only after that the compiler cast this value to a double, which then remains 0. Try with :
double x= (h-i)/(double)h;
double y= (h-i)/(double)h;