- #1
- 3,021
- 7
so the following program uses a user defined function called epotential which is basically a function of the form f(x)=c/x where c is a constant.
I am using a for loop to evaluate the function from -0.5 to +0.5 and incrementing by 0.1
The problem is that I do not want it to evalute f(0) since it is undefined.
I thought that I could simply put "if (x!=0)...evaluate the function"
but this is not working and I do not see what is wrong with that logic.
Can someone help me out here?
Here is the output
x= V=
-0.5 -144
-0.4 -180
-0.3 -240
-0.2 -360
-0.1 -720
-2.77556e-017 -2.59407e+018
0.1 720
0.2 360
0.3 240
0.4 180
0.5 144
I am using a for loop to evaluate the function from -0.5 to +0.5 and incrementing by 0.1
The problem is that I do not want it to evalute f(0) since it is undefined.
I thought that I could simply put "if (x!=0)...evaluate the function"
but this is not working and I do not see what is wrong with that logic.
Can someone help me out here?
Code:
#include <iostream>
#include <fstream> // needed for outfile
using namespace std;
double epotential (double charge, double dist); // function prototype
int main ()
{
ofstream outfile;
outfile.open ("ePotential.txt"); // opens textfile
//declare and initialize objects
double charge=8.0*0.000000001;
double dist;
double V;
outfile <<"x= " << '\t' << "V= " <<endl << endl; //cout to textfile
cout << "x= " << '\t' << "V= " <<endl << endl; //cout to screen
double inc = 0.1; // increment in for loop
double left_bound = -0.5; // left bound of domain of x
double right_bound = 0.5; // right bound of domain of x
for (dist= left_bound; dist <= right_bound; dist+=inc)
{
if (dist != 0) // I do not want it to output V if dist = 0
// why does this not work?!
V=epotential(charge, dist); // loops over domain of x
outfile << dist << '\t' << V << endl; // sends output to textfile
cout << dist << '\t' << V << endl; // sends output to screen
}
system ("PAUSE"); // for Dev C++ compiler
return 0;
}
//function that calculates the electric potential of a charged particle in 1-dim
/*---------------------------------------------------------------------*/
/*---------------------------------------------------------------------*/
double epotential (double q, double r)
{
double V;
double k=9.0*1000000000;
V=k*(q/r);
return (V);
}
Here is the output
x= V=
-0.5 -144
-0.4 -180
-0.3 -240
-0.2 -360
-0.1 -720
-2.77556e-017 -2.59407e+018
0.1 720
0.2 360
0.3 240
0.4 180
0.5 144