为什么我查找两个数字的所有除数的方法不起作用

Why is my method for finding all divisors for two numbers isn't working

所以我做了一个 while 循环来查找给定数字的所有除数,如下所示

int a,b;
int temp =0;
cout << "Enter the first number : ";
cin  >> a;
cout << "Enter the second number : ";
cin >> b;
int smallestNum = a<b?a:b;
while(true)
    {
        temp++;
        if(a%temp == 0 && b%temp == 0) cout << temp << ", ";
        if (temp == smallestNum) break;
    }
    cout << "are all the divisors for both numbers";

它按预期工作,但是当我尝试在 for 循环中做同样的事情时,它没有按计划进行

int a,b;
int temp;
cout << "Enter the first number : ";
cin  >> a;
cout << "Enter the second number : ";
cin  >> b;
temp = a<b?a:b;
for (int i; i == temp; i++)
{
    if(a%i==0 && b%i==0) cout << i << ", ";
}
cout << "are all the divisors for both numbers";

我什至找不到我的代码中的问题来解决它,我该如何解决????

for 循环将迭代,只要条件是 true,你的条件是 i == temp(通常)false,你应该将其更改为 i != temp