求一个数的除数

Finding divisors of a number

本文关键字:一个      更新时间:2023-10-16

我试图编写一个程序来查找用户给出的数字的除数。我的程序正在编译,但它不能正常工作。

#include <iostream>
using namespace std ;
int main () {
    int a,x,y,z,p ;
    int d [z] ;
    y=0 ;
    cout << "Please give me the number you want me to check for dividors" << endl ;
    cin >> a ;
    for (x=2;x<a;x++){
        if(a%x==0)
            d[y]=x ;
            y++ ;
    }
    if (y==0){
        cout << a <<" has no dividors except itself and 1 and therefore, " << a <<" is a prime" << endl ;
    }
    else 
        cout << a <<" has " << y <<" dividors except itself and 1 and this dividors are :" << endl ;
        for (p=0;p<=y;p++){
            cout << d[p] <<endl ;
        }
    return 0 ;
} 

我想加上这句话作为评论,但是我还没有足够的声誉。

无论如何,我认为问题在于你的最后一个for循环。当y是数组d[]中的除数时,你迭代到p <= yd[y]是越界的,循环应该只迭代p < y