C语言 如何在C中找到除法的余数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6993982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:20:13  来源:igfitidea点击:

How to find the remainder of a division in C?

cdivision

提问by Vivek

Which is the best way to find out whether the division of two numbers will return a remainder? Let us take for example, I have an array with values {3,5,7,8,9,17,19}. Now I need to find the perfect divisor of 51 from the above array. Is there any simpler way to solve this?

找出两个数字相除是否会返回余数的最佳方法是什么?让我们举个例子,我有一个值为 {3,5,7,8,9,17,19} 的数组。现在我需要从上面的数组中找到 51 的完美除数。有没有更简单的方法来解决这个问题?

回答by Mircea Nistor

You can use the %operator to find the remainder of a division, and compare the result with 0.

您可以使用%运算符查找除法的余数,并将结果与​​ 进行比较0

Example:

例子:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

回答by MByD

Use the modulus operator %, it returns the remainder.

使用模运算符%,它返回余数。

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

回答by hari

All the above answers are correct. Just providing with your dataset to find perfect divisor:

以上所有答案都是正确的。只需提供您的数据集即可找到完美的除数:

#include <stdio.h>

int main() 
{

int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;

for (i=0 ; i < 7; i++) {
    if (j % arr[i] == 0)
        printf("%d is the perfect divisor of %d\n", arr[i], j);
}

return 0;
}