C ++中的求和程序问题

时间:2013-11-05 01:41:17

标签: c++ math

我是初学者C ++编码器(一般是编程初学者),我似乎遇到了一个问题。我的教授给了我这个项目,我似乎在大多数情况下把它归为正确,但我总是得到一个错误的答案。对于我的计划,当 40 2.00 输入 1.00 时,我会继续 42 作为最终答案strong>表示l, 0.01 表示p)。我很感激任何帮助,并提前感谢任何建议或提示。

enter image description here

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace 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;
}  

2 个答案:

答案 0 :(得分:1)

我没有声称理解你的申请,只是看看计算的结构,可能是P的价值与比率b /(b + l)相比留下一个“转” )?

如果是这样,那么在进入while循环之前向P添加更新就可以了,即插入P计算,P(i = 0)= p,一次之前。因此,为了清楚“else”,我使用了代码:

else
    {
        cout << "\n";
        P = p; // added this line: P(i=0) = p
        while(b / (b + l) > P) {
            P += p * pow((1 - p),num);
            num++;
        }
        cout << "It is optimal to order ";
        cout << num + 1 << " products. " << endl;
    }

给出输出:

It is optimal to order 40 products. 

这当然可能不是错误的真正来源,但至少可以给你一些额外的想法。

答案 1 :(得分:0)

给出算法,答案的数学是合理的。你确定答案是40吗?在最后一行,您需要num并添加1给您42。你确定它不是减1吗?我同意nhgrif关于可读性的一些评论,但因为你是新手,我现在就让它滑动。我更关心为什么或为什么不在你的cout那里num + 1。据我所知,该计划完全符合预期。