Skip to content

Latest commit

 

History

History
58 lines (41 loc) · 1.3 KB

File metadata and controls

58 lines (41 loc) · 1.3 KB

C 程序:显示数字因数

原文: https://www.programiz.com/c-programming/examples/factors-number

在此示例中,您将学习查找用户输入的整数的所有因数。

要理解此示例,您应该了解以下 C 编程主题:


该程序从用户处获取一个正整数,并显示该数字的所有正因子。


正整数的因数

#include <stdio.h>
int main() {
    int num, i;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Factors of %d are: ", num);
    for (i = 1; i <= num; ++i) {
        if (num % i == 0) {
            printf("%d ", i);
        }
    }
    return 0;
} 

输出

Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60 

在程序中,用户输入的正整数存储在num中。

重复执行for循环,直到i <= num< code> is false. =>

在每次迭代中,检查num是否可被i完全整除。i成为num的条件。

if (num % i == 0) {
            printf("%d ", i);
} 

然后i的值增加 1。