C++ 额外的;0“;分解数字时在输出中

C++ 额外的;0“;分解数字时在输出中,c++,function,factors,C++,Function,Factors,编写一个函数int fact(int n),该函数显示整数n的因子,并返回因子数。使用用户输入在main()中调用此函数 #包括 使用名称空间std; int-fact(int-n); int main(){ int n,因子; cout>n; 因子=事实(n); coutFact()始终返回0,因此此行打印0 cout << factor; cout关键部分是“并返回因子的数量”。您不能这样做。请记下因子的数量: int事实(int n) { 整数计数=0; 对于(int i

编写一个函数
int fact(int n)
,该函数显示整数
n
的因子,并返回因子数。使用用户输入在
main()
中调用此函数

#包括
使用名称空间std;
int-fact(int-n);
int main(){
int n,因子;
cout>n;
因子=事实(n);
coutFact()始终返回0,因此此行打印0

  cout << factor;
cout关键部分是“并返回因子的数量”。您不能这样做。请记下因子的数量:

int事实(int n)
{
整数计数=0;

对于(int i=1;i您应该在
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;
}
int事实(int n)
{
整数计数=0;
对于(int i=1;i
#包括
#包括
向量事实(int-n);
int main(){
int n;
std::cout>n;
标准::向量因子=事实(n);
用于(自动i:系数){

std::cout代码的主要问题是函数总是返回零。您需要保持因子计数并返回它

此外,循环持续的时间比需要的时间长,因此代码性能差。您可以使用
n
的平方根作为
for
循环的限制。例如:

int fact(int n)
{
    if (n < 1) return 0;

    int res = 0;
    int limit = sqrt(n);
    for (int i = 1; i <= limit; ++i) 
    {
        if (n % i == 0)
        {
            res += 2;
            cout << i << " - " << n/i << endl;
        }
    }
    if (limit * limit == n)
    {
        --res;
    }
    
    return res;
}
返回的值是9

下面是另一种方法。它不使用平方根。相反,它通过使用
i
的平方作为循环限制来保持较低的循环数

int fact(int n)
{
    if (n < 1) return 0;

    int res = 0;
    int i = 1;
    int i_square = i * i;
    while (i_square < n)
    {
        if (n % i == 0)
        {
            res += 2;
            cout << i << " - " << n/i << endl;
        }
        
        ++i;
        i_square = i * i;
    }
    if (i_square == n)
    {
        ++res;
        cout << i << " - " << n/i << endl;
    }
    
    return res;
}
int事实(int n)
{
如果(n<1)返回0;
int res=0;
int i=1;
int i_平方=i*i;
而(i_平方cout Thi final
0
来自这一行:
cout您实际上应该计数。将变量设置为0,并在每次当前显示
i
时递增。然后在函数末尾返回count变量,而不是返回0。谢谢。但是我如何找到因子的数量?例如,当用户输入6时,函数n显示“1,2,3,6”,并返回4作为因子数;这是一个非常好的点。计算一些结果并返回其他结果不是一个好的程序设计。将所有因子作为向量返回是最自然的。并且可以从向量的大小获得计数。
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
int fact(int n)
{
    if (n < 1) return 0;

    int res = 0;
    int i = 1;
    int i_square = i * i;
    while (i_square < n)
    {
        if (n % i == 0)
        {
            res += 2;
            cout << i << " - " << n/i << endl;
        }
        
        ++i;
        i_square = i * i;
    }
    if (i_square == n)
    {
        ++res;
        cout << i << " - " << n/i << endl;
    }
    
    return res;
}