c++ - 分解数字时输出中的额外 "0"

标签 c++ function factors

写一个函数 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/

相关文章:

c++ - 构建 jesteress 哈希算法

javascript - 如何使用一个 forEach 循环来迭代两个不同的数组?

linux - 如何从 `func`获取 `callq func@PLT`的实际地址

javascript - 在 JavaScript 中从一组数字中获取公因数

c++ - 替换 av_read_frame() 以减少延迟

c++ - 删除 Tesseract 中的处理日志

c++ - 为什么 Visual Studio 在没有优化的情况下可以正确编译此函数,但在优化时却编译错误?

swift - swift中嵌套函数的实际用途是什么?

python - 为什么我的除数函数在某些情况下不起作用?

r - 将两个因素合二为一?