Hey guys, I'm a beginner C++ coder (and beginner at programming in general), and I seem to have run into a problem. My professor assigned me this project and I seem to have it down right for the most part, but I keep getting an answer that's wrong. For my program, I keep getting 42 as the final answer when it should be 40 (entering 1.00 for b, 2.00 for l, and 0.01 for p). I'd appreciate any help, and thanks in advance for any suggestions or tips.
#include <iostream>
#include <cstdlib>
#include <cmath>
usingnamespace std;
int main()
{
double b, l, p, num, P;
num = P = 0;
cout << "Enter the net profit, net loss, and the probabilty ";
cout << "of the products being sold respectively: ";
cin >> b >> l >> p;
if (p <= 0 || p >= 1)
{
cout << "\n";
cout << "The probability is either too large or small. " << endl;
cout << "Please try again." << endl;
}
else
{
cout << "\n";
while(b / (b + l) > P)
P +=p * pow((1 - p),num), num++;
cout << "It is optimal to order ";
cout << num + 1 << " products. " << endl;
}
system("PAUSE");
return 0;
}
Alright.
Problem #1: num contains at the end of the loop the number of terms you added to P. However, s is the last number in the series q = [0, 1, ..., s]. s = length(q) - 1.
Problem #2: You check whether P < b/(b+l) only after you've added one more term, by which point P is already greater than or equal to b/(b+l), so num was incremented by one time too many.
#include <iostream>
#include <cstdlib>
#include <cmath>
usingnamespace std;
int main()
{
double netProfit, netLoss, probability, sum, S;
cout << "Enter the net profit, net loss, and the probability ";
cout << "of the products being sold respectively: ";
cin >> netProfit >> netLoss >> probability;
if ( probability <= 0 || probability >= 1 )
{
cout << "\n";
cout << "The probability is either too large or small. ";
cout << "Please try again." << endl;
}
else
{
cout << "\n";
sum = 0;
S = probability;
while((netProfit / (netProfit + netLoss) > S))
{
S +=probability * pow((1 - probability),sum);
sum++;
}
cout << "It is optimal to order ";
cout << sum + 1 << " products. " << endl;
}
system("PAUSE");
return 0;
}
No. This time I set S (big P in last) = probability (old p in last) instead of 0. I seem to get 40 now, just want to see if it actually solves the issue or if I'm getting a coincidental answer. You can try out the code for yourself if you'd like...thanks.
Mmh... Yes, I believe that should work. You had a fixed offset of 2 for all inputs, so If you're getting the right output for the same overall algorithm, it's probably alright.