首页 文章

用什么代替模数? [关闭]

提问于
浏览
-2

我正在编写一个模拟循环式cpu调度程序的程序 . 在 timestamp (命令行中的变量输入)时间单位数之后,调度程序应将该进程向下移动到队列的底部并继续下一个节点 .

我无法在计算周期结束时进行计算,我首先尝试使用模数,但我意识到这很糟糕 . 然后我尝试使用文字计算,甚至抛出浮动演员,但它仍然无法正常工作 . 当工作的attibute为0时,该陈述为真,而对于所有其他工作值,该陈述为false .

我尝试过的:

if ((queue->worked % timestamp) != 0)
if ((queue->worked - (timestamp * (queue->worked / timestamp))) == 0)
if ((float) (queue->worked - (float) (timestamp * (float) (queue->worked / timestamp))) == 0)

我还想知道是否有更好的方法这样做,以便我可以完全避免模数 .

以下是一些相关代码:

struct node {
    double process_id;
    int arrival_time;
    int cpu_time;
    int worked;
    struct node *nextElement;
};

void round_robin(nodeptr firstNode, int timestamp) {
    nodeptr queue = firstNode;

    if ((queue->worked % timestamp) == 0) {
        queue->worked++;
        current_time++;
    }
    else {
        tmpptr = queue;
        queue = queue->nextElement;
        add_to_bottom(tmpptr, queue);
    }
}

这是一组样本 . 这些是文本文件中的行,由main函数读入并存储为节点的链接列表 .

2001  0  20
 2002  1  10
 2005  2  15
 2007  3   4

其中列表示进程ID,到达时间和进程计算所需的时间(以毫秒为单位) .

指向第一个节点(进程2001)的指针传递给函数以及作为参数传递的整数(./main 10)

该函数遍历列表并模拟循环式cpu调度程序 .

一步一步:所以如果我为时间戳输入10 :(输出现在不重要)

Process 2001 should calculate for 10 milliseconds, then get send to the back of the list.
Process 2002 will calculate for 10 and finish.
Process 2005 will calculate for 10 milliseconds, get send to the back.
Process 2007 will calculate for 4 and be done.
Process 2001 was went to the back and now runs for 10 more and finishes.
Process 2005 calculates for the remaining 5 and the program is now done.

编辑:

我添加了一个printf,在if中显示“If!\ n”,在else中显示“Else!\ n”,并且如果一次打印出来(工作初始化为0),那么每隔一次该节点是跑 . 它只输入if为零值,在工作增加后它不会再次进入并陷入无限循环,将第一个进程放到最后 .

If!
Else!
If!
Else!
If!
Else!
If!
Else!
Else!
Else!
Else!
...until it eventually segfaults after about 900 lines

1 回答

  • 1

    % 在C中不是模数而是余数 . 如果您不将 int 成员更改为 unsigned ,请不要在签名类型(例如 int )上使用它 . 在 unsigned ,您可以保证 a % b 始终在 0 .. b-1 范围内 .

相关问题