如何用一笔总和获得积极产品的负面因素

时间:2012-12-11 02:23:59

标签: c++

我可能没有在标题中解释得这么好,因为我真的不知道如何在标题的长度上解释它所以我为此道歉。无论如何这是我目前的代码:

// Gets the product that is used to get the factors
cout << "Enter a number that you want to be factored" << endl;
cin >> y;

system("cls");

// Gets the sum from the user that the two factors need to add up to
cout << "Input the sum that is needed" << endl;
cin >> neededSum;

secondary = y;
system("cls");

// Lists the factors that add up to the specified sum
cout << "The numbers that add up to " << neededSum << " are:" << endl;
for (int i = 0; i < 100; i++)
{
    x++;
    increment++;
    y = secondary / x;
    product = x * y;
    if (product == secondary)
    {
        sum = x + y;
        if (sum == neededSum)
        {
            cout << x << " and " << y << endl;
        }
    }
}

基本上,产品会列出该产品的所有因素。然后,它将所有因素加在一起,直到找到加起来为指定总和的因子。

但是,如果指定的总和为负值,例如'-11',那么它将不起作用,因为'28'(一个例子)的因子是4和7而不是-4和-7。我需要想办法解决这个问题,以便知道什么时候需要-4和-7而不是正反转。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

假装x和y为负数:

if (product == secondary)
{
    sum = x + y;
    if (sum == neededSum)
    {
        cout << x << " and " << y << endl;
    }
    else if (-sum == neededSum)
    {
        cout << -x << " and " << -y << endl;
    }
}