用双循环分解数字
Factoring Numbers with a Double Loop
问题&示例: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;
}
我已经破解了将近一个小时,以至于我不再理解这个代码的逻辑。如果有人能解决这个问题或向我解释有缺陷的代码的逻辑,我将不胜感激。
您需要为每个数字重新初始化值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;
}
https://ideone.com/KvFFDf
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 通过递归进行因子分解
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 有人能分解一下这个c++模板的语法吗
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 在 C++ 中分解数字
- 下面的代码是如何工作的?它输出分解的数字并且功能齐全,我只是不明白它是如何做到的
- 将数字串分解为结构的向量
- 如何将int分解为数字并以相同的顺序为向量分配数字
- 使用指数符号找到数字的主要分解
- 如何使用字符串数组来分解一个数字的单个数字
- 在 Javascript 中分解一个数字
- 数字误差的质因数分解
- 将一串数字分解为26以下数字的计数方法
- 用双循环分解数字
- 如何优化这个c程序来找到一个数字的质因数分解