如何理解c中的模数 [英] How to make sense of modulo in c

查看:99
本文介绍了如何理解c中的模数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解c语言中的这个模数.
例如:

i am not understanding this modulo in c languge.
For example:

#include <stdio.h>
#include<math.h>

int main()
{
    int my_input[] = {23, 22, 21, 20, 19, 18};
    int n, mod;
    int nbr_items = sizeof(my_input) / sizeof(my_input[0]);

    for (n = 0; n < nbr_items; n++)
    {
        mod = my_input[n] % 4;
        printf("%d modulo %d --> %d\n", my_input[n], 4, mod);
    }
}

给出:

23 modulo 4 --> 3
22 modulo 4 --> 2
21 modulo 4 --> 1
20 modulo 4 --> 0
19 modulo 4 --> 3
18 modulo 4 --> 2

我希望有一个我能理解的数字.
本质上,我试图测试一个数字是否可以被 4 整除.

I would have expected a number that i can make sense of.
Essentially i am trying to test if a number is divisible by 4.

推荐答案

C 中的取模运算符将给出一个数除以另一个数时剩下的余数.例如,23 % 4 将导致 3,因为 23 不能被 4 整除,并且剩下 3 的余数.

The modulo operator in C will give the remainder that is left over when one number is divided by another. For example, 23 % 4 will result in 3 since 23 is not evenly divisible by 4, and a remainder of 3 is left over.

如果你想输出一个数是否能被4整除,你需要输出的不仅仅是mod结果.本质上,如果 mod = 0,那么您就知道一个数可以被另一个数整除.

If you want to output whether or not a number is divisible by 4, you need to output something other than just the mod result. Essentially, if mod = 0 than you know that one number is divisible by another.

如果你想输出数字是否可以被4整除,我建议创建一个新的字符,根据mod操作的结果设置为y"(是)或n"(否).以下是生成更有意义的输出的一种可能实现:

If you want to output whether or not the number is divisible by 4, I would suggest creating a new character that is set to "y" (yes) or "n" (no) depending on the result of the mod operation. Below is one possible implementation to generate a more meaningful output:

#include <stdio.h>
#include <ctype.h>
#include <math.h>

int main()
{
    int my_input[] = {23, 22, 21, 20, 19, 18};
    int n, mod;
    char is_divisible;
    int nbr_items = sizeof(my_input) / sizeof(my_input[0]);

    for (n = 0; n < nbr_items; n++)
    {
        mod = my_input[n] % 4;
        is_divisible = "y" ? mod == 0 : "n";
        printf("%d modulo %d --> %c\n", my_input[n], 4, is_divisible);
    }
}

这将给出以下内容:

23 modulo 4 --> n
22 modulo 4 --> n
21 modulo 4 --> n
20 modulo 4 --> y
19 modulo 4 --> n
18 modulo 4 --> n

这篇关于如何理解c中的模数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆