How to find the remainder of a division in C?

前端 未结 3 1607
迷失自我
迷失自我 2021-02-13 12:13

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

相关标签:
3条回答
  • 2021-02-13 12:48

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

    Example:

    if (number % divisor == 0)
    {
        //code for perfect divisor
    }
    else
    {
        //the number doesn't divide perfectly by divisor
    }
    
    0 讨论(0)
  • 2021-02-13 12:59

    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;
    }
    
    0 讨论(0)
  • 2021-02-13 13:09

    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);
    }
    
    0 讨论(0)
提交回复
热议问题