I’m doing an assignment for a stats class, and I’m new to programming. I don’t want to ask a stupid question, but I’ve searched and can’t find an answer.
Here is my code:
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
double pareto(double x, double alpha, double beta)
{
double val = beta * pow(alpha, beta) / pow(x, beta+1);
if( alpha <= 0 ) printf("error");
else if( beta <= 0 ) printf("error");
else if( alpha >= x) return(0);
else return(val);
}
int main()
{
double x;
double alpha;
double beta;
scanf("%lf", &x);
scanf("%lf", &alpha);
scanf("%lf", &beta);
printf("%f\n", pareto(x,alpha,beta));
return 0;
}
When I test the code as follows:
echo 3 -2 1 | ./paretodens
I get the output:
error0.000000
I would like it to be simply “error”. I hope my question makes sense. Thanks for any help.
You can make your program die if there’s an error:
That way the function will never return and you don’t call the final print statement at all.
Otherwise note that
paretohas no method for signaling an error to the caller! If you wanted to continue execution after an error, you would have to redesign your function to allow for an error state to happen and to be communicated.Since you’re new: also note that your code can be made a lot shorter, since you don’t need an
elseafter areturnorexit:And notice that you don’t need to perform the computation unless you know that you need it!