Reputation: 894
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.
Upvotes: 0
Views: 183
Reputation: 10027
If I understand you correctly, you want to print either 'error' or the correct return value from the function, but not both. The problem is that you call the pareto
function from inside a call to printf
. The pareto
function itself has a call to printf, that's why your code prints both 'error' and the return value.
Personally, I would clean it up as follows:
double pareto(double x, double alpha, double beta)
{
if (alpha <= 0 || beta <= 0)
return -1;
if (alpha >= x)
return 0;
return beta*pow(alpha,beta)/pow(x,beta+1);
}
int main()
{
double x;
double alpha;
double beta;
double val;
scanf("%lf", &x);
scanf("%lf", &alpha);
scanf("%lf", &beta);
val = pareto(x,alpha,beta);
if (val < 0)
printf("error");
else
printf("%f\n", val);
return 0;
}
Upvotes: 0
Reputation: 477514
You can make your program die if there's an error:
if (alpha <= 0)
{
printf("error\n");
exit(EXIT_FAILURE);
}
That way the function will never return and you don't call the final print statement at all.
Otherwise note that pareto
has 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 else
after a return
or exit
:
double pareto(double x, double alpha, double beta)
{
if (alpha <= 0 || beta <= 0) { printf("Error\n"); exit(EXIT_FAILURE); }
return alpha >= 0 ? 0 : beta * pow(alpha, beta) / pow(x, beta + 1);
}
And notice that you don't need to perform the computation unless you know that you need it!
Upvotes: 4
Reputation: 51920
This is always getting executed:
printf("%f\n", pareto(x,alpha,beta));
You don't have a condition at all for that. Also, your pareto() function will sometimes return no specified value. You should fix that and make it always return some specific value.
Upvotes: 1