c - 用什么代替模数?

标签 c if-statement modulus

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

当我在一个周期结束时,我在尝试计算时遇到了麻烦,我首先尝试使用模数,但我意识到这很糟糕。然后我尝试使用文字计算,甚至加入了浮点转换,但它仍然不起作用。当工作属性为 0 时,该语句为 true;当工作属性为所有其他值时,该语句为 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);
    }
}

这是一组示例。这些是文本文件中的行,由主函数读入并存储为节点的链接列表。

 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”的 printf,它打印 if 一次(worked 初始化为 0),然后每隔一次打印 else该节点已运行。它只进入 if 值为 0,worked 递增后,它不会再次进入,并陷入将第一个进程结束的无限循环中。

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

最佳答案

C 中的

% 不是模数而是余数。如果您不知道它在做什么,请不要在像 int 这样的有符号类型上使用它。如果您将 int 成员更改为 unsigned,也许您的担忧就会消失。在unsigned上,您可以保证a % b始终落在0..b-1范围内。

关于c - 用什么代替模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723372/

相关文章:

python - 如果我向函数添加 "else",为什么会得到一个空列表?

c++如果满足所有条件

c++ - 为什么短路模数在 Release模式下不正确?

c - 模运算似乎不适用于所有值的 64 位值

c - fopen - C 中作为流数据的原始数据

c - gtk_box_pack_start 和 gtk_container_add 有什么区别?

c++ - 通过 C 中的偏移量调用函数

python - 在 if-elif-else 语句中定义值时打印小计?名称错误问题[Python 2.7]

c++ - 如何在 C++ 中找到模乘逆

c - 堆排序 "visual"树打印额外的零