gpt4 book ai didi

c++ - 我的逻辑在哪里失败?

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:06 26 4
gpt4 key购买 nike

我完成了工作——但我的输出很奇怪。我基本上是在尝试比较一堆对象,如果它们共享 ttns 并且它们的时间到了——那么它们需要重新计算它们的 ttns。检查完所有主机后,我增加时钟并重试。目标是找到第一台可以通过检查而不会发生碰撞的主机。这基本上是一个网络模拟,如果两个主机同时发送 (CLOCK),它会进行一些退避计算。我进行了检查以确保主机没有检查自己——我知道我的预期输出是什么,但事实并非如此。我已经完成了几次,但找不到我的逻辑错误。任何指针?

// 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com