此程序从用户那里获取一个正整数,并显示该数的所有因子。
示例:显示一个数的因子
#include <iostream>
using namespace std;
int main() {
int n, i;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factors of " << n << " are: ";
for(i = 1; i <= n; ++i) {
if(n % i == 0)
cout << i << " ";
}
return 0;
}
输出
Enter a positive integer: 60 Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
在此程序中,用户输入的整数存储在变量 n 中。
然后,for 循环以初始条件 i = 1
执行,并检查 n 是否能被 i 整除。如果 n 能被 i 整除,则 i 是 n 的因子。
在每次迭代中,i 的值都会更新(加 1)。
此过程一直持续到测试条件 i <= n
为 false,即,此程序检查用户输入的数 n 是否能被从 1 到 n 的所有数整除,并显示该数的所有因子。