首页 > 解决方案 > 如何找到数组中每个数字的因数

问题描述

我有一个用户输入的数字数组,然后程序按升序对其进行排序。我只需要找到一种方法来获取数组中每个数字的因子并将其打印出来

#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;
}

我希望它用“(数字)的因子是......”“(下一个数字)的因子是......”打印数组中的每个数字

等等

标签: c++

解决方案


最后的 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);

那么你的代码很适合你:

现场演示


推荐阅读