c++ - 如何找到数组中每个数字的因数
问题描述
我有一个用户输入的数字数组,然后程序按升序对其进行排序。我只需要找到一种方法来获取数组中每个数字的因子并将其打印出来
#include "stdafx.h"
#include <iostream>
#include <limits>
#define MAX 200
using namespace std;
int arr[MAX];
int n, i, j, k;
int temp;
int main()
{
//array declaration
int arr[MAX];
int n, i, j;
int temp;
//read total number of elements to read
cout << "Enter total number of numbers to read: ";
cin >> n;
//check bound
if (n<0 || n>MAX)
{
cout << "Input valid range!!!" << endl;
return -1;
}
//read n elements
for (i = 0; i < n; i++)
{
cout << "Enter element [" << i + 1 << "] ";
cin >> arr[i];
cout << endl;
}
//print input elements
cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
//sorting - ASCENDING ORDER
for (i = 0; i<n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//print sorted array elements
cout << endl;
cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl <<endl;
//trying to find factors
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++i)
{
if (arr[i] % k == 0)
cout << k << endl;
}
system ("pause")
return 0;
}
我希望它用“(数字)的因子是......”“(下一个数字)的因子是......”打印数组中的每个数字
等等
解决方案
最后的 for 循环应该是 loop withk
并且你忘记了 increment k
。您还应该编写i
-loop:
//trying to find factors
for (i = 0; i < n; i++)
{
cout << "Factors of " << arr[i] << " are: " << endl;
for (k = 1; k <= arr[i]; ++k)
{
if (arr[i] % k == 0)
cout << k << endl;
}
}
另外,正如@LocTran 所指出的,外循环的上限应该是n-1
. arr
或者,您可以使用std::sort
如下方式轻松排序:
std::sort(arr, arr+n);
那么你的代码很适合你:
推荐阅读
- kubernetes - 我可以从文件中创建 openshift 4.3 中的秘密吗?
- wiremock - 用于 https 调用的 Wiremock json 存根
- elasticsearch - 如何在 Laravel 中实现弹性搜索以自动完成
- pandas - 大熊猫中的Groupby聚合并根据流行度对创建的列表进行排序
- javascript - Chrome 扩展:chrome.webNavigation 无法更新 URL
- plot - 后跟 readline() 时,绘图命令失败
- python - 在 python 中将数组分隔符设置为换行符
- sqlite - Deduping 表连接到自身
- swift - 如何编写一个包含 2 个闭包的 Swift 函数
- mysql - 在 MySQL 中查询以获取当前季度之前的季度的记录