问题&示例:http://prntscr.com/atfkmo
以下解决方案收到错误的输出:http://prntscr.com/atfm5w
int main()
{
int n;
int f = 1;
cout << "Enter an integer: ";
cin >> n;
for (int i = 1; i <= n; i++) // 1st loop to get list of numbers from 1-n.
{
cout << "| " << i << ": ";
while (f <= i) { // 2nd loop to get list of factors for each number from 1-n
if (i%f == 0) // divisibility check
{
cout << f;
}
f++;
}
cout << endl;
}
我已经黑了近一个小时了,我不再理解这段代码的逻辑了。如果有人能够解决这个问题或者向我解释有缺陷的代码的逻辑,我将非常感激,所以我可以解决它。
答案 0 :(得分:1)
您需要为每个号码重新初始化值f=1
:
int main()
{
int n;
int f = 1;
cout << "Enter an integer: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
f=1; // reinitialize
cout << "| " << i << ": ";
while (f <= i) {
if (i%f == 0)
{
cout << f;
}
f++;
}
cout<<"\n";
}
cout << endl;
}