写一个函数 int fact(int n)
显示整数 n
的因数,并返回因子数。在 main()
中调用此函数有用户输入
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
如果我输入 7
, 我得到 1,7,0
.我如何删除这个 0
以及如何找到因子的数量?
最佳答案
你应该算在你的int fact()
功能。将变量设置为 0 并在每次当前显示 i 时递增。然后在函数的末尾而不是返回 0 返回计数变量。
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
关于c++ - 分解数字时输出中的额外 "0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65109875/