c++ - C++ 中求和程序的问题

标签 c++ math

我是一名初学者 C++ 编码员(一般而言也是编程初学者),我似乎遇到了一个问题。我的教授给我分配了这个项目,我似乎大部分时间都做对了,但我总是得到错误的答案。对于我的程序,当它应该是 40 时,我总是得到 42 作为最终答案(为 b 输入 1.002.00,p 为 0.01)。我将不胜感激任何帮助,并提前感谢您提供任何建议或提示。

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

最佳答案

我并不声称了解您的应用程序,只是查看计算结构,与比率 b/(b + l )?

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

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. 

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

关于c++ - C++ 中求和程序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19780581/

相关文章:

c++ - 如何在 C++ 中实现贝塞尔曲线?

numpy 函数给出不正确的结果 - 手动和 Excel 检查

java - 适合新手的 Java self 描述数字程序

具有模板作为参数的类的 C++ 成员函数特化

c++ - 使用new关键字限制实例数量

c++ - 关于重载解析的奇怪编译错误

SQL 数据上的 PHP 数学

c++ - 读取中间名可选的文件

c++ - 试图替换 C++ 字符串中的字符,完全卡住

c# - UInt64 和 "The operation overflows at compile time in checked mode"- CS0220