我完成了工作-但我的输出很奇怪。我基本上是在尝试比较一堆对象,如果它们共享ttns并且时间用完了-那么它们需要重新计算其ttns。检查所有主机后,我增加时钟并重试。目的是找到可以通过检查而不会碰撞的拳头主机。这基本上是对网络的模拟,如果两个主机同时发送(时钟),则该网络会进行一些补偿计算。我进行了检查,以确保主机未对自身进行检查-我知道我的预期输出是,不是。我已经完成了几次,但是找不到逻辑错误。有指针吗?
// Should insert n number as argument 1 on the command line.
#include <iostream>
#include <vector>
#include <stdlib.h> // srand(), time()
static int CLOCK = 0;
class Host{
private:
int sid;
int cc;
int ttns;
public:
Host();
int get_sid(){ return sid; }
void set_sid(int id){ sid = id; }
int get_cc(){ return cc; }
void inc_cc(){ cc += 1; }
int get_ttns(){ return ttns; }
void new_ttns(){ ttns = (rand()%(cc+1))+CLOCK+1; }
};
Host::Host(){
sid = -666;
cc = 0;
ttns = 0;
}
bool work(std::vector<Host> &hosts){
int count = 0;
for(CLOCK = 0; /*INFINITE*/; CLOCK++){
for(int i = 0; i < hosts.size(); i++){
count = 0;
for(int n = 0; n < hosts.size(); n++){
if( (i != n) && /* host i doesn't compare to host n */
(hosts[i].get_ttns() == hosts[n].get_ttns()) &&/* host i and n share ttns */
(hosts[i].get_ttns() == CLOCK) /* host i ttns = now */
){
hosts[i].inc_cc();
hosts[i].new_ttns();
count = -666; // collision occured
}
count++;
}
if ( count == hosts.size() ){
std::cout << "Host " << hosts[i].get_sid() << "\nTTNS: " << hosts[i].get_ttns();
std::cout << std::endl;
return false;
}
}
}
return true; // pretty pointless
}
int main(int argc, char *argv[]){
srand(time(NULL));
std::vector<Host> hosts;
// Push hosts into vector
int nhosts = atoi(argv[1]);
for(int i = 0; i < nhosts; i++){
Host newhost;
newhost.set_sid(i);
hosts.push_back(newhost);
}
while (work(hosts)){
; // hang out
}
return 0;
}
最佳答案
错误之一可能在此行中:
(hosts[i].get_ttns() == CLOCK)
您无法比较这点,因为CLOCK是全局的,并且增加了一个以上的主机。这意味着主机没有单调的时钟。
也许你想要这个:
(hosts[i].get_ttns() <= CLOCK
关于c++ - 我的逻辑在哪里失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5562654/