【发布时间】:2021-11-15 06:32:12
【问题描述】:
我目前正在研究一种可靠性设计算法,我在此视频https://www.youtube.com/watch?v=uJOmqBwENB8 上找到了该算法。我用 C++ 编写了代码,但是我遇到了一个问题,在其中一个循环中,一些迭代被跳过了。这是整个代码:
#include <iostream>
#include <cmath>
#include <vector>
#include <utility>
using namespace std;
int main(){
int n;
cin>>n;
int cost[n],num_available[n],max_cost;
double rel[n];
for(int i=0;i<n;i++)
cin>>cost[i];
for(int i=0;i<n;i++)
cin>>rel[i];
for(int i=0;i<n;i++)
cin>>num_available[i];
cin>>max_cost;
vector<pair<double,int>> resSet;
resSet.push_back(make_pair(1,0));
for(int i=0;i<n;i++){
vector<pair<double,int>> tempSet;
for(int j=0;j<num_available[i];j++){
for(int pos=0;pos<resSet.size();pos++){
int sum_left_costs=0;
for(int k=i+1;k<n;k++)
sum_left_costs+=cost[k];
if(sum_left_costs+resSet[pos].second+cost[i]*(j+1)>max_cost)
break;
tempSet.push_back
(make_pair(resSet[pos].first*(1-pow((1-rel[i]),j+1))
,resSet[pos].second+cost[i]*(j+1)));
}
}
for(int i=0;i<tempSet.size();i++){
cout<<"Reliability: "<<tempSet[i].first<<
", Price: "<<tempSet[i].second<<endl;
}
resSet=tempSet;
cout<<endl;
}
double maxRel=0,pos;
for(int i=0;i<resSet.size();i++){
if(maxRel<resSet[i].first){
pos=i;
maxRel=resSet[i].first;
}
}
cout<<"Best Reliability: "<<resSet[pos].first<<
" for price: "<<resSet[pos].second;
return 0;
}
无论如何,在试图找出问题的同时,我在循环中添加了一些代码更改,只是为了看看循环经过了多少次迭代:
for(int i=0;i<n;i++){
cout<<"i="<<i<<", ";
vector<pair<double,int>> tempSet;
for(int j=0;j<num_available[i];j++){
cout<<"j="<<j<<", ";
for(int pos=0;pos<resSet.size();pos++){
cout<<"pos="<<pos<<", ";
int sum_left_costs=0;
for(int k=i+1;k<n;k++)
sum_left_costs+=cost[k];
if(sum_left_costs+resSet[pos].second+cost[i]*(j+1)>max_cost)
break;
tempSet.push_back
(make_pair(resSet[pos].first*(1-pow((1-rel[i]),j+1))
,resSet[pos].second+cost[i]*(j+1)));
}
}
resSet=tempSet;
cout<<endl;
}
现在,一旦我执行了程序,结果如下:
Input:
3
30 15 20
0.9 0.8 0.5
2 3 3
105
Output:
i=0, j=0, pos=0, j=1, pos=0,
i=1, j=0, pos=0, pos=1, j=1, pos=0, pos=1, j=2, pos=0, pos=1,
i=2, j=0, pos=0, pos=1, pos=2, pos=3, j=1, pos=0, pos=1, j=2, pos=0, pos=1,
Best Reliability: 0.63 for price: 105
但预期的输出应该是:
i=0, j=0, pos=0, j=1, pos=0,
i=1, j=0, pos=0, pos=1, j=1, pos=0, pos=1, j=2, pos=0, pos=1,
i=2, j=0, pos=0, pos=1, pos=2, pos=3, j=1, pos=0, pos=1,pos=2,pos=3, j=2, pos=0, pos=1, pos=2, pos=3
Best Reliability: 0.648 for price: 100
Any ideas what could cause these problems?
P.S. Yes i know I need to learn how to use a debugger.
【问题讨论】:
-
你期望得到的输出是什么?
-
是的,我知道我需要学习如何使用调试器。越早开始,您越早获得好处。
-
仅供参考,可变长度数组,例如
int cost[n]不是标准 C++。我建议您将它们替换为std::vector。 -
这可能是正确的,但乍一看,我希望这里是 j 而不是 i:for(int k=i+1;k
-
它可能会碰到你的
break语句并跳出for(int pos=0;pos<resSet.size();pos++)循环。当然,我真的无法说出预期的结果