【问题标题】:Using modulus operator in C produce some strange result [closed]在 C 中使用模数运算符会产生一些奇怪的结果 [关闭]
【发布时间】:2014-03-19 09:10:19
【问题描述】:

C语言如何进行取模运算?

请阅读下面的代码。

#include <stdio.h>

int main(void)
{       
    int i = 100;

    printf("%d\n", i%100);
    printf("%d\n", i%240);
    printf("%d\n", i%40);
    printf("%d\n", i%10);


    return 0;
}

结果是

$ ./modulus
0
100
20
0

请告诉我如何正确使用它。

编辑

对不起,我在代码中犯了一个错误。除法应该像下面的代码一样在另一边。

printf("%d\n", 100%i);
printf("%d\n", 240%i);
printf("%d\n", 40%i);
printf("%d\n", 10%i);

当值乘以 100 时,我期望得到 0

我很抱歉这个错误。但是,伙计们,请撤消我的反对意见。

【问题讨论】:

  • 你期待什么结果?
  • 你用对了。
  • 你想要什么输出。因为你的程序是正确的。
  • How to make modulus operation in C language? 根据你已经使用的:)
  • @MarounMaroun 不正确:"modulus and remainder are not the same"

标签: c operators


【解决方案1】:

嗯,它工作正常。你期待看到什么?

模运算符(模运算的实现),得到除法余数。例如:

a % b = c

可以改写为a = b * d + c,其中a、b、c、d是整数。

所以,100 % 40 = 20,因为 100 = 40 * 2 + 20

【讨论】:

    【解决方案2】:

    modulo division 的结果是给定数字的 integer division 的余数(正数)。

    这意味着:

    100 / 100 = 1, remainder 0
    => 100 mod 100 = 0
    
    100 / 240 = 0, remainder 100
    => 100 mod 240 = 100
    
    100 / 40 = 2, remainder 20
    => 100 mod 40 = 20
    
    100 / 10 = 10, remainder 0
    => 100 mod 10 = 0
    

    【讨论】:

    • “模除法的结果是给定数字的整数除法的余数。” ---> modulus and remainder are not the same
    • @GrijeshChauhan - 谢谢 :-) - 添加了 on the positive scale
    • 也为negative添加技巧,检查相关问答我也不确定这是正确的。
    【解决方案3】:

    你得到的输出是正确的。当您执行两个数字的整数除法时,模运算符会返回余数。

    你的情况

    • 100 mod 100 = 0 作为 100 = 100*1 + 0
    • 100 mod 240 = 100 作为 100 = 240*0 + 100
    • 100 mod 40 = 20 作为 100 = 40*2 + 20
    • 100 mod 10 = 10 作为 100 = 10*10 + 0

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多